How to execute two mysql queries as one in PHP/MYSQL?
You'll have to use the MySQLi extension if you don't want to execute a query twice:
if (mysqli_multi_query($link, $query))
{
$result1 = mysqli_store_result($link);
$result2 = null;
if (mysqli_more_results($link))
{
mysqli_next_result($link);
$result2 = mysqli_store_result($link);
}
// do something with both result sets.
if ($result1)
mysqli_free_result($result1);
if ($result2)
mysqli_free_result($result2);
}
Update: Apparently possible by passing a flag to mysql_connect()
. See Executing multiple SQL queries in one statement with PHP Nevertheless, any current reader should avoid using the mysql_
-class of functions and prefer PDO.
You can't do that using the regular mysql-api in PHP. Just execute two queries. The second one will be so fast that it won't matter. This is a typical example of micro optimization. Don't worry about it.
For the record, it can be done using mysqli and the mysqli_multi_query-function.
As others have answered, the mysqli API can execute multi-queries with the msyqli_multi_query() function.
For what it's worth, PDO supports multi-query by default, and you can iterate over the multiple result sets of your multiple queries:
$stmt = $dbh->prepare("
select sql_calc_found_rows * from foo limit 1 ;
select found_rows()");
$stmt->execute();
do {
while ($row = $stmt->fetch()) {
print_r($row);
}
} while ($stmt->nextRowset());
However, multi-query is pretty widely considered a bad idea for security reasons. If you aren't careful about how you construct your query strings, you can actually get the exact type of SQL injection vulnerability shown in the classic "Little Bobby Tables" XKCD cartoon. When using an API that restrict you to single-query, that can't happen.