且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用PHP执行多个MYSQL查询

更新时间:2023-11-30 11:41:10

不要一次运行一堆查询.通常,一项操作的成功取决于所有其他操作的正确执行,因此,您不能随便推土机,就好像出现问题时都没出错一样.

Don't run a bunch of queries at once. Usually the success of one depends on all the other operations having been performed correctly, so you can't just bulldozer along as if nothing's gone wrong when there's a problem.

您可以这样做:

$queries = [
  "CREATE TEMPORARY TABLE tmp SELECT * FROM event_categoriesBU WHERE id = 1",
  "UPDATE tmp SET id=100 WHERE id = 1",
  "INSERT INTO event_categoriesBU SELECT * FROM tmp WHERE id = 100"
];

foreach ($query as $query) {
  $stmt = $conn->prepare($query);
  $stmt->execute();
}

别忘了启用异常,以便进行任何查询故障将停止您的过程,而不是使事情失去控制.

Don't forget to enable exceptions so that any query failures will stop your process instead of the thing running out of control.

您不使用multi_query的原因是因为该函数不支持占位符值.如果需要在此查询中引入某种类型的用户数据,则需要使用bind_param以便安全地进行操作.没有占位符值,您将面临SQL注入错误,并且其中一个错误足以使您的整个应用程序容易受到攻击.

The reason you don't use multi_query is because that function does not support placeholder values. Should you need to introduce user data of some kind in this query you need to use bind_param in order to do it safely. Without placeholder values you're exposed to SQL injection bugs, and a single one of those is enough to make your entire application vulnerable.

值得注意的是,PDO比mysqli更具灵活性和适应性,因此,如果您对mysqli的投入不多,则值得考虑进行切换.

It's worth noting that PDO is a lot more flexible and adaptable than mysqli so if you're not too heavily invested in mysqli, it's worth considering a switch.