29

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?

1

8 Answers 8

32

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.

4
  • 3
    I am basically concerned about the performance, which I think will decrease if we'll hit the database two times.
    – djmzfKnm
    Apr 29, 2009 at 14:06
  • 1
    Do a benchmark if you're not convinced. The time it will take to execute the SELECT FOUND_ROWS() query and retrieve the result is negligable. You already have the connection, and the result set is extremely small (just one integer).
    – Emil H
    Apr 29, 2009 at 14:10
  • 8
    BTW, If you're worried about performance you should be spending your time trying to get rid of the LIKE '%prashant%' statement. That's possibly a real performance issue. As a rule of thumb: The bottle neck for most php applications is not in php at all, but rather in the database. If you want to spend time optimizing your application, spend it reviewing your indices and EXPLAIN:ing your queries.
    – Emil H
    Apr 29, 2009 at 14:11
  • My first query is insert and second one is getting Id of the first one. running to php execute is out of question since records are inserted into table very fast.
    – AaA
    Apr 17, 2020 at 14:58
8

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.

4

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);
}
3

Using SQL_CALC_FOUND_ROWS you can't.

The row count available through FOUND_ROWS() is transient and not intended to be available past the statement following the SELECT SQL_CALC_FOUND_ROWS statement.

As someone noted in your earlier question, using SQL_CALC_FOUND_ROWS is frequently slower than just getting a count.

Perhaps you'd be best off doing this as as subquery:

SELECT 
 (select count(*) from my_table WHERE Name LIKE '%prashant%') 
as total_rows,
Id, Name FROM my_table WHERE Name LIKE '%prashant%' LIMIT 0, 10;
3
  • SQL_CALC_FOUND_ROWS is slower, but at dev.mysql.com/doc/refman/5.0/en/… link I found "However, this is faster than running the query again without LIMIT, because the result set need not be sent to the client. " ??
    – djmzfKnm
    Apr 29, 2009 at 14:00
  • 1
    But not in this case, since the query can't use indices. SQL_CALC_FOUND_ROWS will result in a single table scan, while your subquery will result in two, and therefore is much slower. Also, You've forgotten a comma after total_rows.
    – Emil H
    Apr 29, 2009 at 14:00
  • 1
    Yes, well, you're not running the query again without the limit. You're running a count(*), which sends one row. Really, Emil H has a good point -- it's a micro optimization of dubious value. Either run two queries, or if you absolutely must do this, do it as a subquery as I've explained. (Emil H, thanks for pointing out teh missing comma.)
    – tpdi
    Apr 29, 2009 at 14:06
3

You have to use MySQLi, below code works well

<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$query  = "SELECT CURRENT_USER();";
$query .= "SELECT Name FROM City ORDER BY ID LIMIT 20, 5";

/* execute multi query */
if ($mysqli->multi_query($query)) {
    do {
        /* store first result set */
        if ($result = $mysqli->store_result()) {
            while ($row = $result->fetch_row()) {
                printf("%s\n", $row[0]);
            }
            $result->free();
        }
        /* print divider */
        if ($mysqli->more_results()) {
            printf("-----------------\n");
        }
    } while ($mysqli->next_result());
}

/* close connection */
$mysqli->close();
?>
1

Like this:

$result1 = mysql_query($query1);
$result2 = mysql_query($query2);

// do something with the 2 result sets...

if ($result1)
    mysql_free_result($result1);

if ($result2)
    mysql_free_result($result2);
3
  • 1
    Didn't he want to avoid executing mysql_query twice? Apr 29, 2009 at 13:55
  • 1
    Yes, I want to avoid mysql querries twice. And in @Jon Benedicto answer, he's executing two queries. :(
    – djmzfKnm
    Apr 29, 2009 at 13:57
  • I've just posted another answer that shows how to do execute both queries in one go using MySQLi. Apr 29, 2009 at 14:10
1

It says on the PHP site that multiple queries are NOT permitted (EDIT: This is only true for the mysql extension. mysqli and PDO allow multiple queries) . So you can't do it in PHP, BUT, why can't you just execute that query in another mysql_query call, (like Jon's example)? It should still give you the correct result if you use the same connection. Also, mysql_num_rows may help also.

1
  • This is only true for the mysql extension. mysqli and PDO allow multiple queries. Apr 29, 2009 at 14:05
0

Yes it is possible without using MySQLi extension.

Simply use CLIENT_MULTI_STATEMENTS in mysql_connect's 5th argument.

Refer to the comments below Husni's post for more information.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.