3

How can i prevent it from loading the same table row all over again and never stopping ? My head can't take it ... I know i somehow created an infinite loop so i searched on internet and i saw people doing almost the same but somehow it worked for them.

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";
}

?>
Fast Arrows
  • 259
  • 2
  • 11

3 Answers3

3

When you use

while($row) {

You are effectively creating an endless loop. Because $row is a defined variable, it's a turthy value - this makes it essentially become

while (true) {

What you want instead is to fetch each row, meaning that you must supply the mysqli_fetch_assoc() as the argument to your while. You also want to check the number of rows instead, as you are now fetching the first row (and it will not be visible in the loop).

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";
}

You should also be aware that your code is vulnerable for SQL-injection attacks, and you should use prepared statements with MySQLi and bind your values instead of injecting the variables directly in your query.

Qirel
  • 25,449
  • 7
  • 45
  • 62
0

Change this:

$row = mysqli_fetch_assoc($result);

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

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

To this:

if (mysqli_num_rows($result) > 0)
{

    while($row = mysqli_fetch_assoc($result))
    {
        echo htmlspecialchars($row["sender"] . ": " . $row["msg"]);
        echo "<br><br>";
    }
}
Ivan86
  • 5,695
  • 2
  • 14
  • 30
0

You can first count with mysqli_num_rows if your query contains any records or not and then can use mysqli_fetch_assoc if records are there like below:

$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>";
    }
 }

Always use Prepared Statements to make Queries more Secure

Amit Gupta
  • 2,771
  • 2
  • 17
  • 31