无法调用超过100个INSERT查询

时间:2017-04-07 13:51:19

标签: php mysqli

我必须插入1000条记录才能从文件读取并插入到数据库,但我的代码工作时间不超过100次。它说internal server 500但是当我运行100次以下的代码时,它工作正常。是否有任何设置我必须申请插入超过100条记录?

这是我的代码:

<?php 
    $servername = "**";
    $username = "**";
    $password = "**"; 
    $dbname = "**";

    $con=mysqli_connect($servername, $username, $password,$dbname);

    for($i=0; $i<400; $i++){

        $query = mysqli_query($con,"INSERT INTO table_name (column1, column2, column3)
                                    VALUES (value1, value2, value3)");          
    }

    $query->close();
    $con->close();
?>

它只能工作100次。如果我设置循环运行超过那个,它不起任何想法吗?

2 个答案:

答案 0 :(得分:0)

我不确定这是否会消除您的问题,但尝试减少代码中的总数据库调用总是更好。

由于您在同一个表上进行INSERT,因此您可以在单个查询中执行所有操作。在循环中构建单个查询,然后在循环结束后仅使用mysqli_query()一次。

代码:

$values="";
for($i=0; $i<400; $i++){
    $values.=($i==0?"",",")."('value1','value2','value3')";
}
$query=mysqli_query($con,"INSERT INTO table_name (column1, column2, column3) VALUES $values;

答案 1 :(得分:0)

小心)

function interpolate($message, array $context = [], $openTag = '{', $closeTag = '}')
{
    // build a replacement array with braces around the context keys
    $replace = array();
    foreach ($context as $key => $val) {
        // check that the value can be casted to string
        if (!is_array($val) && (!is_object($val) || method_exists($val, '__toString'))) {
            $replace[$openTag . $key . $closeTag] = $val;
        }
    }

    // interpolate replacement values into the message and return
    return strtr($message, $replace);
}

function interpolatedQuery($conn, $query, array $context = [])
{
    $sql = interpolate($query, $context);
    $result = mysqli_query($sql);
    if (!$result && mysqli_connect_errno() && in_array(mysqli_connect_errno(), [1213, 1614])) {
        // deadlock
        usleep(50000);
        return interpolatedQuery($conn, $query, array $context);
    }
    return $result;
}

$values = [];
foreach ($records as $record) {
    $values[] = interpolate(
        '({value1}, {value2}, {value3})',
        [
            'value1' => $record['id'],
            'value2' => '"' . mysqli_real_escape_string($record['name']) . '"',
            'value3' => 'NULL'
        ]
    );
}

if (count($values)) {
    $chunks = array_chunk($values, 1000);
    foreach ($chunks as $chunk) {
        interpolatedQuery(
            'INSERT INTO table_name (column1, column2, column3) VALUES{values}',
            [
                'values' => implode(', ', $chunk)
            ]
        );
    }
}