PHP的MySQLi多个插入(PHP MySQLi Multiple Inserts)

2019-07-19 22:01发布

我不知道是否准备语句的工作一样具有多个值的正常的mysql_query。

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

VS

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

如果我用事先准备好的声明中循环,是MySQL的优化后台插件像它会在第一段代码来工作的,还是只是像每一个时间值运行的循环中的第一块代码?

Answer 1:

我继续跑,其中一个查询使用准备好的语句的测试,另建立整个查询随后执行。 我可能不会做,我想知道易于理解。

这里是我的测试代码。 我想准备语句排序的阻碍执行,直到$ 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();

?>


Answer 2:

如果你在一个循环中使用准备好的语句,它会比运行,因为每个分析时间只需要用事先准备好的声明,一旦完成了原始查询效率更高。 所以,不,这是不一样的,到那个程度。



Answer 3:

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查询,一旦将它插入。 但这不是批量插入一次。



文章来源: PHP MySQLi Multiple Inserts
标签: php mysqli