PHP MySQLi多个插入 [英] PHP MySQLi Multiple Inserts

查看:50
本文介绍了PHP MySQLi多个插入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm wondering if prepared statements work the same as a normal mysql_query with multiple VALUES.

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

VS

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

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

If I use the prepared statement in a loop, is MySQL optimizing the insert in the background to work like it would in the first piece of code there, or is it just like running the first piece of code inside a loop with one value each time ?

推荐答案

我继续进行了测试,其中一个查询使用准备好的语句,另一个查询构建整个查询,然后执行该语句.我可能不会使我想知道的内容变得容易理解.

I went ahead and ran a test where one query uses a prepared statement, and the other builds the entire query then executes that. I'm probably not making what I'm wanting to know easy to understand.

这是我的测试代码.我在想准备好的语句会推迟执行,直到调用$ stmt-> close()对其进行优化为止.事实并非如此,因为使用real_escape_string构建查询的测试至少快10倍.

Here's my test code. I was thinking prepared statements sort of held back execution until a $stmt->close() was called to optimize it or something. That doesn't appear to be the case though as the test that builds the query using real_escape_string is at least 10 times faster.

<?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();

?>

这篇关于PHP MySQLi多个插入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆