2 回答

TA貢獻1784條經驗 獲得超9個贊
在你的循環中...
while($rows) {
因為您不會更改循環中的值 - 它始終是它開始的值,因此永遠不會終止,認為您想使用...
$result2 = mysqli_query($db, $sql2);
while($rows = mysqli_fetch_assoc($result2)) {
這將依次獲取每一行并在移動到下一行之前顯示輸出。
您可能還想將表定義移到循環之外,除非您希望每一行都在它自己的表中。

TA貢獻1877條經驗 獲得超6個贊
Nigel 確實提供了解決方案,但讓我們討論其他明顯的問題。我已經重新編寫了您的代碼,進行了兩個主要更改,您可能仍然需要進行一些調整,因為我不熟悉您的 db 或其他命名變量。
1 - 準備好的聲明
它如何幫助以及有什么作用與其一百次重新回答這個問題,其他人在解釋它方面做得更好:
準備好的語句如何防止 SQL 注入攻擊?
輔助函數- 在您更好地了解準備好的語句的工作原理后,您將需要此功能。
https://phpdelusions.net/mysqli/simple
2 - 面向對象
我用面向對象的語法重寫了這個。我發現它不那么冗長,而且通常更容易理解。你用語法改變你贏得了什么做準備好的語句,因為它們通常涉及更多的步驟(但為了更大的好處)
$sql2 = "SELECT a_id, u_id, answer, a_datetime, user_id, username FROM answer LEFT JOIN user ON answer.u_id = user.user_id WHERE q_id = ?";
$stmt -> $con -> prepare($sql2);
$stmt -> bind_param("s", $pid);
$stmt -> execute();
$stmt -> store_result();
$stmt -> bind_result($aid, $uid, $answer, $date, $userid, $username);
echo '<table border=2>';
while($stmt -> fetch()) {
echo '<tr>';
echo '<td>Answered by: '. $username .'</td>';
echo '</tr>';
echo '<tr>';
echo '<td>'. $answer .'</td>';
echo '</tr>';
echo '<tr>';
echo '<td>'. $date .'</td>';
echo '</tr>';
}
echo '</table>';
$stmt -> free_result();
$stmt -> close();
$con -> close();
在我們挑選頭發時,您應該盡量不要回顯過多的 HTML。您可以在while循環內關閉 php ,它的工作方式相同。我還修復了您遇到的一些 HTML 問題。(應該使用<tbody>,只是為了好玩,我<thead>也在那里扔了一個
// after bind result in the code above
?>
<table>
<thead>
<th>Answered by</th>
<th>Answer</th>
<th>Date</th>
</thead>
<tbody>
<?php
while($stmt -> fetch()) {
?>
<tr>
<td><?php echo $username;?></td>
</tr>
<tr>
<td><?php echo $answer;?></td>
</tr>
<tr>
<td><?php echo $date;?></td>
</tr>
<?php
}
?>
</tbody>
</table>
- 2 回答
- 0 關注
- 156 瀏覽
添加回答
舉報