Using PHP to execute multiple MYSQL Queries

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.

You can do it like this:

$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.

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.

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.

Leave a Comment