note 125597 added to pdostatement.fetchall
| From: | herhor67 at interia dot pl | Date: | Sat, 12 Dec 2020 10:00:18 +0000 |
| Subject: | note 125597 added to pdostatement.fetchall | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-215975@lists.php.net to get a copy of this message | ||
I noticed quite a weird (at least for me) behaviour. Maybe it can help someone who will struggle
with this too.
<?php
$stmt = new PDOStatement();
$foo = $stmt->fetchAll();
var_dump($foo);
$stmt = $pdo->prepare('SELECT VERSION()');
$foo = $stmt->fetchAll();
var_dump($foo);
$stmt = $pdo->prepare("INSERT INTO
tblnm (date) VALUES (NOW())");
$stmt->execute();
$foo = $stmt->fetchAll();
var_dump($foo);
$stmt = $pdo->query("INSERT INTO tblnm (date) VALUES (NOW())");
$foo = $stmt->fetchAll();
var_dump($foo);
?>
The first is just an empty object, so $foo === bool(false)
The second one is not executed, so $foo === array(0) {}
The third and fourth throw exception at fetchAll():
"General error: 2014 Cannot execute queries while other unbuffered queries are active. Consider
using PDOStatement::fetchAll(). Alternatively, [...] you may enable query buffering by setting the
PDO::MYSQL_ATTR_USE_BUFFERED_QUERY attribute."
fetchAll() is already used, and changing the above attribute between true and false changes nothing.
This is probably caused by the INSERT not having any return value. We could use RETURNING in the
sql, but it's quite new, so may not yet be supported everywhere.
What finally worked for me, was $pdo->exec() and lastInsertId(), because ID is the only column I
needed anyway.
<?php
$count = $pdo->exec('INSERT INTO tblnm (date) VALUES (NOW())');
$foo = $pdo->lastInsertId();
var_dump($foo);
?>
Then e.g. $foo === string(2) "93"
----
Server IP: 45.112.84.4
Probable Submitter: 45.112.85.244 (proxied: 91.192.199.30)
----
Manual Page -- http://php.net/manual/en/pdostatement.fetchall.php
Edit -- https://master.php.net/note/edit/125597
Del: integrated -- https://master.php.net/note/delete/125597/integrated
Del: useless -- https://master.php.net/note/delete/125597/useless
Del: bad code -- https://master.php.net/note/delete/125597/bad+code
Del: spam -- https://master.php.net/note/delete/125597/spam
Del: non-english -- https://master.php.net/note/delete/125597/non-english
Del: in docs -- https://master.php.net/note/delete/125597/in+docs
Del: other reasons-- https://master.php.net/note/delete/125597
Reject -- https://master.php.net/note/reject/125597
Search -- https://master.php.net/manage/user-notes.php