如何使用准备好的语句一次在mysql数据库中插入多行? [英] How to insert multiple rows in a mysql database at once with prepared statements?

查看:167
本文介绍了如何使用准备好的语句一次在mysql数据库中插入多行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正尝试在 this中使用staticsan的答案问题以获取准备好的陈述. 让我们举个例子:

I am trying to use staticsan´s answer in this question for prepared statements. Lets take this example:

$stmt = $mysqli->prepare("INSERT INTO something (userid, time, title) VALUES (?, ?, ?)");
$stmt->bind_param('iis', $userid, time(), $title);
$stmt->execute();

在staticsan的答案中,爆破数组是将所有值添加到mysql语句中,以便最终我们可以仅用一条语句将多个数据插入数据库中. 在我的示例中该怎么做?

In staticsan´s answer imploding the array is adding all the values into the mysql statement so that in the end we can insert multiple data into the database with just one statement. How would this be done in my example?

推荐答案

这是完全有效的:

$stmt = $mysqli->prepare("INSERT INTO something (userid, time, title) VALUES (?, ?, ?)");

$stmt->bind_param('iis', $userid, time(), $title);
$stmt->execute();

$stmt->bind_param('iis', $userid, time(), $title);
$stmt->execute();

$stmt->bind_param('iis', $userid, time(), $title);
$stmt->execute();

$stmt->bind_param('iis', $userid, time(), $title);
$stmt->execute();

您可以遍历每次插入,绑定和执行的值数组.它不会像您链接的示例中的批量插入一样快,但是会更加安全.

You can foreach over your array of values to insert and bind and execute each time. It wont be quite as fast as the bulk insert in the example you linked, but it will be more secure.

这篇关于如何使用准备好的语句一次在mysql数据库中插入多行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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