by: Mark Alexander Bain
It’s very easy to send SQL queries to a MYSQL database and process the results (see How to Run MySQL Queries with PHP). However, running a number of queries one after another can be time consuming and memory intensive.
Fortunately PHP enables the programmer to run a number of queries at the same time and then process the returned results one record set at a time. The PHP programmer does this by using PHP’s mysqli object and its multi_query method.
Sending Multiple Queries to MySQL from PHP
Rather than repeatedly sending queries to the database it is possible to send a number of them at the same time. The first step, as always, is to instantiate the mysqli object:
With the connection in place the next stage is to create a string consisting of several SQL statements (remembering to separate each of them with a semi-colon):
Then the multi_query method sends the query to the database:
The PHP programmer will then need to process the results returned from the multiple queries. This is, of course, slightly more involved than handling a single query because more than one record set may be returned.
Processing the Results from Multiple Queries
When the PHP programmer processes the results from their queries they must:
- Step though the record sets by using the next_result method
- Load the current record set by using the store_result method
The end result is something like:
Here only one recordset will be returned and processed (since only a single select statement is being used).
The PHP programmer sends queries to a MySQL programmer by creating a mysqli object. This object connects to the database and then accepts a single SQL statement via the query method. Multiple SQL statements can be sent to the database but this time programmer must use the multi_query method. The result of each query depends on the type of query sent.
Only select statements return a set of records. All queries return true or false depending on the query’s success or failure. Once the PHP application has received the record set then the results can be processed and presented to the web page user or used elsewhere in the application itself.