This is possible with mysqli_multi_query () .
Example:
<?php $mysqli = new mysqli($host, $user, $password, $database); // create string of queries separated by ; $query = "INSERT INTO images (project_id, user_id, image_name, date_created, link_to_file, link_to_thumbnail, given_name) VALUES ('$project_id', '$user_id', '$image_name', '$date_created', '$link_to_file', '$thumbnail', '$ImageName');"; $query .= "INSERT INTO images_history (project_id, user_id, image_name, date_created, link_to_file, link_to_thumbnail, given_name, day, month, year) VALUES ('$project_id', '$user_id', '$image_name', '$date_created', '$link_to_file', '$thumbnail', '$ImageName', '$day', '$month', '$year');"; // execute query - $result is false if the first query failed $result = mysqli_multi_query($mysqli, $query); if ($result) { do { // grab the result of the next query if (($result = mysqli_store_result($mysqli)) === false && mysqli_error($mysqli) != '') { echo "Query failed: " . mysqli_error($mysqli); } } while (mysqli_more_results($mysqli) && mysqli_next_result($mysqli)); // while there are more results } else { echo "First query failed..." . mysqli_error($mysqli); }
The key is that you must use mysqli_multi_query
if you want to execute multiple queries in one call. For security reasons, mysqli_query
will not execute multiple queries to prevent SQL injection.
Also consider the behavior of mysqli_store_result
. It returns FALSE
if the query does not have a result set (which INSERT
queries are not), so you should also check mysqli_error
to see that it returns an empty string meaning that the INSERT
was successful.
Cm:
mysqli_multi_query
mysqli_more_results
mysqli_next_result
mysqli_store_result