PHP MySQLi多个插入
我想知道准备好的语句是否与具有多个值的普通mysql\u查询一样工作PHP MySQLi多个插入,php,mysqli,Php,Mysqli,我想知道准备好的语句是否与具有多个值的普通mysql\u查询一样工作 INSERT INTO table (a,b) VALUES ('a','b'), ('c','d'); VS 如果我在循环中使用prepared语句,MySQL是在后台优化insert,使其像在第一段代码中那样工作,还是就像在循环中每次运行一个值的第一段代码一样?如果在循环中使用prepared语句,它将比每次运行原始查询更高效,因为只需要对准备好的语句执行一次分析。因此,不,在这一点上是不一样的。我继续运行了一个测试,其
INSERT INTO table (a,b) VALUES ('a','b'), ('c','d');
VS
如果我在循环中使用prepared语句,MySQL是在后台优化insert,使其像在第一段代码中那样工作,还是就像在循环中每次运行一个值的第一段代码一样?如果在循环中使用prepared语句,它将比每次运行原始查询更高效,因为只需要对准备好的语句执行一次分析。因此,不,在这一点上是不一样的。我继续运行了一个测试,其中一个查询使用准备好的语句,另一个生成整个查询,然后执行该语句。我可能没有让我想知道的东西容易理解 这是我的测试代码。我在想,在调用$stmt->close()对其进行优化之前,预先准备好的语句有点延迟执行。但情况似乎并非如此,因为使用real_escape_字符串构建查询的测试速度至少要快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();
?>
此函数首先准备一个包含多行值的插入查询,然后插入一次。但这不是一次性批量插入。但如果使用多行插入语法,则速度会更快,因为使用多行插入语法时,将只向数据库发送一次查询,因此多个请求的开销会减少。我希望使用类似的方法(多个插入),因为此答案标记正确,这是优化的解决方案吗?另外,“使用real\u escape\u字符串构建查询的测试速度至少快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;
}
}