php组装数据批量插入,比单条循环插入数据快很多


/**
 * 批量生成2000个,32位CDKEY,并加入到redis队列里
 * Created by PhpStorm.
 * User: xiexiaoping
 * Date: 2023-10-18
 * Time: 13:33
 */
include_once('connect.php');
include_once('common.php');
include_once('redis.php');

define('CDKEY', 'cdkeylist');
define('CDKEY_MAX', 2000);
define('CDKEY_MIN', 1);

$number = CDKEY_MAX;
if (!is_numeric($number)) {
    return error('数量必须是整形');
}
if ($number > CDKEY_MAX) {
    return error('数量不能大于' . CDKEY_MAX);
}

if ($number < CDKEY_MIN) {
    return error('数量不能小于' . CDKEY_MIN);
}


$random_arr = [];
for ($i = 0; $i < $number; $i++) {
    $random_arr[$i] = getRandom();
}
$num = $redis->lLen(CDKEY);
if ($num > 0) {
    return error('CDKEY已批量生成,无需重复生成');
}
/**
 * 组合数据,批量插入
 */
if (!empty($random_arr)) {
    $sql = sprintf("INSERT INTO m_cdkey (`code`, `create_time`) VALUES ");
    $time = date('Y-m-d H:i:s', time());
    foreach ($random_arr as $item) {
        $itemStr = '( ';
        $itemStr .= sprintf("'%s', '%s'", $item, $time);
        $itemStr .= '),';
        $sql .= $itemStr;
    }

    // 去除最后一个逗号,并且加上结束分号
    $sql = rtrim($sql, ',');
    $sql .= ';';


    if ($conn->query($sql) === TRUE) {
    } else {
        echo "Error: " . $sql . "
"
. $conn->error; } } $sql_query = "SELECT code FROM m_cdkey"; $result = $conn->query($sql_query); $arr = []; if ($result->num_rows > 0) { while ($row = $result->fetch_assoc()) { //$arr[] = $row['code']; $redis->lPush(CDKEY, $row['code']); } } //$redis->lPush(CDKEY,$arr); return success("CDKEY批量生成");

你可能感兴趣的:(php,android,开发语言)