繁体   English   中英

PHP MySQLi 多次插入

[英]PHP MySQLi Multiple Inserts

我想知道准备好的语句是否与具有多个 VALUES 的普通 mysql_query 工作相同。

INSERT INTO table (a,b) VALUES ('a','b'), ('c','d');

VS

$sql = $db->prepare('INSERT INTO table (a,b) VALUES (?, ?);

如果我在循环中使用准备好的语句,MySQL 是在后台优化插入以使其像在那里的第一段代码中一样工作,还是就像在每次使用一个值的循环中运行第一段代码一样?

我继续运行了一个测试,其中一个查询使用准备好的语句,另一个构建整个查询然后执行它。 我可能没有让我想知道的东西易于理解。

这是我的测试代码。 我在想准备好的语句会阻止执行,直到调用 $stmt->close() 来优化它或其他东西。 情况似乎并非如此,因为使用 real_escape_string 构建查询的测试至少快 10 倍。

<?php

$db = new mysqli('localhost', 'user', 'pass', 'test');

$start = microtime(true);
$a = 'a';
$b = 'b';

$sql = $db->prepare('INSERT INTO multi (a,b) VALUES(?, ?)');
$sql->bind_param('ss', $a, $b);
for($i = 0; $i < 10000; $i++)
{
    $a = chr($i % 1);
    $b = chr($i % 2);
    $sql->execute();
}
$sql->close();

echo microtime(true) - $start;

$db->close();

?>

如果在循环中使用准备好的语句,它将比每次运行原始查询更有效,因为分析只需要对准备好的语句进行一次。 所以不,在那种程度上是不一样的。

public function insertMulti($table, $columns = array(), $records = array(), $safe = false) {
    self::$counter++;
    //Make sure the arrays aren't empty
    if (empty($columns) || empty($records)) {
        return false;
    }

    // If set safe to true: set records values to html real escape safe html
    if($safe === true){
        $records = $this->filter($records);
    }

    //Count the number of fields to ensure insertion statements do not exceed the same num
    $number_columns = count($columns);

    //Start a counter for the rows
    $added = 0;

    //Start the query
    $sql = "INSERT INTO " . $table;

    $fields = array();
    //Loop through the columns for insertion preparation
    foreach ($columns as $field) {
        $fields[] = '`' . $field . '`';
    }
    $fields = ' (' . implode(', ', $fields) . ')';

    //Loop through the records to insert
    $values = array();
    foreach ($records as $record) {
        //Only add a record if the values match the number of columns
        if (count($record) == $number_columns) {
            $values[] = '(\'' . implode('\', \'', array_values($record)) . '\')';
            $added++;
        }
    }
    $values = implode(', ', $values);

    $sql .= $fields . ' VALUES ' . $values;
    //echo $sql;
    $query = $this->dbConnection->query($sql);

    if ($this->dbConnection->error) {
        $this->errorLog($this->dbConnection->error, $sql);
        return false;
    } else {
        return $added;
    }
}

此函数首先准备具有多个行值的一个 INSERT 查询并插入一次。 但这不适用于一次批量插入。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM