且构网

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

使用PHP执行多个MYSQL查询

更新时间:2023-11-30 11:54:28

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

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.