简体   繁体   中英

When and How to use Multiple MySQL Queries with PHP (PDO)

What are the benefits of using multiple MySQL queries in a statement, other than to minimize code.

How do you execute, retrieve, and display the results of multiple MySQL queries sent in one statement using PHP (and preferably PDO).

mysql_query() doesn't support multiple queries. However, there are some workarounds:

http://www.dev-explorer.com/articles/multiple-mysql-queries
http://php.net/function.mysql-query

Regardless of which database you are using, it can be more efficient to put multiple queries into one statement. If you perform the queries separately, you have to make a call to the database across the network (or at least, between processes if on the same machine), get a connection to it (including autheticating), pass in the query, return the resultset, and release the connection for each query.

Even if you use connection pooling, you are still passing more requests back and forth than is necessary.

So, for example, if you combine two queries into one, you have saved all of that extra calling back and forth for the second query. The more queries you combine, then, the more efficient your app can become.

For another example, many apps populate lists (such as for dropdownlists) when they start up. That can be a number of queries. Performing them all in one call can accelerate startup time.

I was doing some research tonight and stumbled across this thread. None of the answers above provide a viable solution to this simple problem.

Using the OO Approach, you can perform multiple query statements in a single connection by using the multi_query() method.

$db_connection->multi_query($query);

Queries should be well-formed and separated by semicolons -> ;

see The PHP manual for more details on how to handle SELECT data

Multiple queries on the same call are especially beneficial when you need to work with session variables and temporary tables:

select somecol, @somevar := group_concat( distinct somecol2 separator '|')
from sometbl
where
    somecol LIKE "fueh"
group by somecol;

select somecol2
from  sometbl
where
    somecol LIKE "nyan"
and
    vc_wp regexp concat( '(', @somevar, ')' )
order by somecol;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM