I’m using while($stmt->fetch()) to loop though the results I get from a MySQL Query, and under certain conditions, I’m only getting one result.
I’m guessing this is becuase I’ve got 2 $stmt‘s. but I thought this sort of thing was supported. I guess I’m making a rookie mistake, I’ve been used to non-prepared statements for too long!
$db = mysqlConnect();
$stmt = $db->stmt_init();
$stmt->prepare("SELECT id, uploadtype FROM uploads ORDER BY displayorder DESC");
$stmt->execute();
$stmt->bind_result($id, $uploadtype);
while ($stmt->fetch()) {
echo 'ID = ' . $id . '<br />';
if ($uploadtype == 'single') {
$stmt->prepare("SELECT title, description FROM singles WHERE id = ?");
$stmt->bind_param('i', $id);
$stmt->execute();
$stmt->bind_result($title, $description);
$stmt->fetch();
?>
Title: <? echo $title; ?><br />
Description: <? echo $description; ?><br />
<a href="edit.php?id=<? echo $id; ?>">Edit</a><br />
<?
}
}
This only echo’s one ID. I’m guessing this is the problem because when I use the following, I get all IDs echoed.
$db = mysqlConnect();
$stmt = $db->stmt_init();
$stmt->prepare("SELECT id, uploadtype FROM uploads ORDER BY displayorder DESC");
$stmt->execute();
$stmt->bind_result($id, $uploadtype);
while ($stmt->fetch()) {
echo 'ID = ' . $id . '<br />';
}
How can I get around this problem? I’m thinking I don’t understand prepared statements quite right.
EDIT:
Now changed to this, but getting invalid object or resource mysqli_stmt on line starting <error>.
$db = mysqlConnect();
$stmt = $db->stmt_init();
if (!$limit) {
$stmt->prepare("SELECT id FROM uploads WHERE uploadtype = 'youtube' ORDER BY displayorder DESC");
} else {
$stmt->prepare("SELECT id FROM uploads WHERE uploadtype = 'youtube' ORDER BY displayorder DESC LIMIT 0, ?");
$stmt->bind_param('i', $limit);
}
$stmt->execute();
$stmt->bind_result($id);
while ($stmt->fetch()) {
$stmt2 = $db->stmt_init();
$stmt2->prepare("SELECT title, description, url FROM youtube WHERE id = ?");
<error>$stmt2->bind_param('i', $id);
<error>$stmt2->execute();
<error>$stmt2->bind_result($title, $description, $url);
<error>while ($stmt2->fetch()) {
$title = stripslashes($title);
$description = stripslashes($description);
$url = stripslashes($url);
?>
<class id="item">
<?
if ($gettitle) echo 'Title: ' . $title . '<br/>';
if ($getdescription) echo 'Description: ' . $description . '<br />';
?>
<iframe width="560" height="315" src="<? echo $url; ?>" frameborder="0" allowfullscreen></iframe>
</class><br />
<?
}
}
You need another statement variable. Replace the second usage (
SELECT title...) with a separate variable (e.g.,$stmt2for lack of a better name).Otherwise the next
fetchin the outer loop is run against the second statement.