PHP 正在无休止地加载相同的内容

PHP is loading the same content endlessly

如何防止它再次加载相同的 table 行并且永不停止?我的头受不了……我知道我不知何故创造了一个无限循环,所以我在互联网上搜索,我看到人们做的几乎相同,但不知何故对他们有用。

include_once "additional_code/dbh.inc.php";

session_start();

$savedUsername = $_SESSION["username"];

if (!isset($savedUsername) || empty($savedUsername)) {
    header("location: login.php");
    exit;
}

$sql = "SELECT * FROM messages WHERE sender = $savedUsername";
$result = mysqli_query($conn, $sql);
$row = mysqli_fetch_assoc($result);

if ($row > 0) {
    echo "it works";

    while($row) {
        echo htmlspecialchars($row["sender"] . ": " . $row["msg"]);
        echo "<br><br>";
    }
}
else {
    echo "It doesn't work";
}

?>

改变这个:

$row = mysqli_fetch_assoc($result);

if ($row > 0)
{
    echo "it works";

   while($row)
   {
      echo htmlspecialchars($row["sender"] . ": " . $row["msg"]);
      echo "<br><br>";
   }
}

为此:

if (mysqli_num_rows($result) > 0)
{

    while($row = mysqli_fetch_assoc($result))
    {
        echo htmlspecialchars($row["sender"] . ": " . $row["msg"]);
        echo "<br><br>";
    }
}

当您使用

while($row) {

您实际上是在创建一个无限循环。因为 $row 是一个定义的变量,所以它是一个 turthy 值——这使得它本质上变成了

while (true) {

您想要的是获取每一行,这意味着您必须提供 mysqli_fetch_assoc() 作为 while 的参数。您还想检查 行数 ,因为您现在正在获取第一行(并且它在循环中不可见)。

if (mysqli_num_rows($result)> 0) {
    echo "it works";

    while($row = mysqli_fetch_assoc($result)) {
        echo htmlspecialchars($row["sender"] . ": " . $row["msg"]);
        echo "<br><br>";
    }
}
else {
    echo "It doesn't work";
}

你还应该知道你的代码容易受到 SQL 注入攻击,你应该使用 MySQLi 的准备语句并绑定你的值而不是直接注入变量您的查询。

  • How can I prevent SQL injection in PHP?

如果您的查询包含或不包含任何记录,您可以先使用 mysqli_num_rows 计数,然后如果有记录,则可以使用 mysqli_fetch_assoc,如下所示:

$sql = "SELECT * FROM messages WHERE sender = $savedUsername";
$result = mysqli_query($conn, $sql);
$count = mysqli_num_rows($result);

if ($count > 0) {
    echo "it works";
    while($row = mysqli_fetch_assoc($result)) {
        echo htmlspecialchars($row["sender"] . ": " . $row["msg"]);
        echo "<br><br>";
    }
 }

始终使用准备好的语句使查询更安全