I have encountered strange behavior in PHP regarding prepared statements. The problem with googling did not bear any fruit, so here it is.
Suppose you have this code:
<?php
$db = new mysqli('localhost','root','','test');
$q = 'SELECT text FROM tests';
if($stmt = $db->prepare($q))
{
$stmt->bind_result($clmn);
$stmt->execute();
$stmt->fetch();
echo '</br>'.$clmn;
}
else echo "</br>didn't prepare first";
$q = 'SELECT id FROM tests';
if($stmt = $db->prepare($q))
{
$stmt->bind_result($clmn);
$stmt->execute();
$stmt->fetch();
echo '</br>'.$clmn;
}
else echo "</br>didn't prepare second";
?>
There are only 2 columns and 2 rows with dummy data in the database:

Now, when I run the code, what I expect is output as follows:
foo
1
I get:
foo
didn't prepare second
Now I have done some tests and found out that when I exchange this:
$stmt->fetch();
echo '</br>'.$clmn;
for this:
while($stmt->fetch())
echo '</br>'.$clmn;
I get this result:
foo
bar
1
2
The idea that I have is that the prepared statement cannot be changed until all the lines of the previous one have been selected. Note that it fetch()must return false, and not just the last line, so that the second statement is ready.
- ? XAMPP.