I have a simple piece of code:
$sql = "SELECT * FROM users";
$stmt = $this->conn->prepare($sql);
$stmt->execute();
echo $stmt->rowCount();
This outputs 0
when run with PHP7.
However, this is the wrong/unexpected result.
The expected result is 15
.
If I run the above code in PHP8 I get the expected result.
If I duplicate the line $stmt = $this->conn->prepare($sql);
, as in the code below, I then get the correct value in PHP7.
$sql = "SELECT * FROM users";
$stmt = $this->conn->prepare($sql);
$stmt = $this->conn->prepare($sql);
$stmt->execute();
echo $stmt->rowCount();
My connection is established in the following way:
$this->conn = new PDO('mysql:host=' . DB_SERVER . ';dbname=' . DB_NAME . ';charset=utf8',
DB_USER, DB_PASS,
[PDO::MYSQL_ATTR_INIT_COMMAND =>"SET NAMES utf8;SET time_zone = '" . TIMEZONE . "'"]);
Clearly something is wrong as the second prepare shouldn't be necessary, but I don't know where to start.
Perhaps I'm missing something obvious?
PHP versions I'm using specifically:
PHP 7.2.34
PHP 8.0.8
Clarification
I would like the user rows returned (not the number - that's just to show the problem) - but with PHP7 I get no rows, with PHP8 I get all the requested/existing rows.
Clarification #2
Yes, sorry, I was trying to provide a minimal working example. I do fetch and iterate through the users. For simplicity though, I'm currently just checking the number of rows/users returned:
$users = $stmt->fetchAll(PDO::FETCH_ASSOC);
echo count($users);
The use of rowCount()
was meant to simplify the issue.
The MySQL driver versions are:
mysql (mysqlnd 5.0.12-dev - 20150407
mysql (mysqlnd 8.0.13)
Clarification #3
$stmt->execute();
does return false. My bad - sorry.
However, looking at this question, the output of print_r($stmt->errorInfo());
is:
Array
(
[0] => 00000
[1] =>
[2] =>
)
I've added the following to my DB connection but I'm not getting any more information than the above.
$this->conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
Clarification 4
False trail as "$pdo->errorInfo() refers to the last statement that was successfully executed" https://stackoverflow.com/a/12438685/1489538.