Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PDO multiple queries

Tags:

php

mysql

pdo

As of PHP version 5.3 PDO_MYSQL driver has been repleaced in favour of PDO_MYSQLND. It introduced support for multiple queries.

Though, I can't figure out how to get both result sets if more than one SELECT query has been passed. Both queries have been executed, it can't be that the second one was just dumped.

$db->query("SELECT 1; SELECT 2;")->fetchAll(PDO::FETCH_ASSOC);

Returns:

array(1) {
  [0]=>
  array(1) {
    [1]=>
    string(1) "1"
  }
}
like image 710
Gajus Avatar asked Jun 30 '12 05:06

Gajus


People also ask

Which is better MySQLi or PDO?

Both MySQLi and PDO have their advantages: PDO will work on 12 different database systems, whereas MySQLi will only work with MySQL databases. So, if you have to switch your project to use another database, PDO makes the process easy. You only have to change the connection string and a few queries.

How can I run two SQL queries in PHP?

You can execute multiple SQL queries with multi_query , a built-in function in PHP. The SQL queries should be in a quoted string to make multiple queries with multi_query , but each SQL should be delimited with a semicolon. For the HTML and CSS, you can use the same HTML and CSS code from the previous section.

What does PDO -> query return?

PDO::query() returns a PDOStatement object, or FALSE on failure.

Is PHP PDO secure?

As long as you provide all values per ->execute(array( , as above, yes.


1 Answers

It turns out that you need to use PDOStatement::nextRowset.

$stmt   = $db->query("SELECT 1; SELECT 2;");
$stmt->nextRowset();
var_dump( $stmt->fetchAll(PDO::FETCH_ASSOC) );

This will return result for the second query.

It is a bit odd implementation. It would certainly be easier if multi-query statement would just return both results sets under one array. However, the advantage is that this implementation allows to fetch every query using different FETCH styles.

like image 112
Gajus Avatar answered Sep 16 '22 14:09

Gajus