Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to execute two mysql queries as one in PHP/MYSQL?

Tags:

loops

php

mysql

I have two queries, as following:

SELECT SQL_CALC_FOUND_ROWS Id, Name FROM my_table WHERE Name LIKE '%prashant%' LIMIT 0, 10; SELECT FOUND_ROWS(); 

I want to execute both these queries in a single attempt.

$result = mysql_query($query); 

But then tell me how I will handle each tables set separately. Actually in ASP.NET we uses dataset which handles two queries as

ds.Tables[0]; ds.Tables[1]; .. etc 

How can I do the same using PHP/MYSQL?

like image 342
djmzfKnm Avatar asked Apr 29 '09 13:04

djmzfKnm


People also ask

How run multiple MySQL queries in PHP?

Multiple statements or multi queries must be executed with mysqli::multi_query(). The individual statements of the statement string are separated by semicolon. Then, all result sets returned by the executed statements must be fetched.

How do I merge two MySQL queries?

The MySQL UNION operator is used to combine the result sets of 2 or more SELECT statements. It removes duplicate rows between the various SELECT statements. Each SELECT statement within the UNION operator must have the same number of fields in the result sets with similar data types.

Can I run 2 SQL queries at once?

You can include multiple SQL statements on the SQL query panel. The exceptions are CALL and CREATE PROCEDURE statements. These statements must be used alone in a query.


2 Answers

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.

like image 119
Emil H Avatar answered Oct 02 '22 14:10

Emil H


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.

like image 25
Bill Karwin Avatar answered Oct 02 '22 13:10

Bill Karwin