问题描述:

I have encountered a strange behavior in PHP in regards to prepared statements. Googling the issue didn't bare 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";

?>

The database is just 2 columns and 2 rows with dummy data:

Now when I run the code, what I expect is output like this:

foo

1

What I get is:

foo

didn't prepare second

Now I did a few 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 of the rows of the previous one are fetched. Note that fetch() needs to return false and not just the last row in order for the second statement to get prepared.

Anyone got more insight on this? I've only tested it with XAMPP.

网友答案:

This is most probably because there are still results waiting to be fetched from your first query. Before executing the second query, try:

$stmt->close();

This should clear the buffer allowing further queries to be run.

相关阅读:
Top