下面有两个代码 - 首先使用没有预准备语句的mysqli,第二个使用预准备语句不起作用。在第二个,问题是在while循环中的第二个查询。我可以使用mysqli和预编程语句在循环中使用查询吗?
代码#1有效:
$sql = "SELECT * FROM topics ORDER BY topic_id DESC";
$result = $mysqli->query($sql);
<?php while($row = $result->fetch_assoc()) {
$topic_id = $row['topic_id'];
?>
<div class="brpostova col-md-2">Postova:
<?php
$sql2 = "SELECT * FROM postovi WHERE post_topic = $topic_id ";
$rezultat = $mysqli->query($sql2);
echo $rezultat->num_rows;
?>
</div>
<div class="autor col-md-2">Posted by <a href="#"><?php echo $row['topic_autor']; ?></a></div>
<?php
}
$result->free
?>
代码#2不起作用:
$stmt = $mysqli->prepare("SELECT * FROM topics ORDER BY topic_id DESC");
$stmt->execute();
$stmt->bind_result($id, $sadrzaj, $naslov, $datum, $kategorija, $autor, $sticky, $closed);
<?php while ($stmt->fetch()) {
$topic_id = $id;
?>
<div class="brpostova col-md-2">Postova:
<?php
$post = $mysqli->prepare("SELECT * FROM postovi WHERE post_topic = ? ");
$post->bind_param('i', $topic_id);
$post->execute();
$post->store_result();
$numrows = $post->num_rows;
$post->close();
echo $numrows
?>
</div>
<div class="autor col-md-2">Posted by <a href="#"><?php echo $autor; ?></a></div>
<?php
}
$stmt->free_result();
$stmt->close();
?>