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

前端 未结 8 1005
误落风尘
误落风尘 2020-11-22 13:19

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();
<         


        
8条回答
  •  情深已故
    2020-11-22 13:59

    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.

提交回复
热议问题