Php echo doesn't work when nested in while() under if()

I am new to php and I am struggling to understand what I'm doing wrong with the code below. I've been searching for a solution for an hour now but I can't find this specific problem.

I am running a query to write contents of my table using echo and a while loop.

This code will work:

    while($row = $result->fetch_assoc()) 
    {
        echo "<tr><td>id: " . $row["ID"]. 
        "</td><td>Firstname: " . htmlspecialchars($row["FIRSTNAME"]). 
        "</td><td>Lastname: " . htmlspecialchars($row["LASTNAME"]). "</td></tr>";
    } 

But if it's inside my IF function, the echo's will not work. I tested the IF function and it executes, because the first echo before the while() works.

if ($result->num_rows > 0) 
{
    echo "IF has worked, attempting while loop: </br>";
    while($row = $result->fetch_assoc()) 
    {
        echo "<tr><td>id: " . $row["ID"]. 
        "</td><td>Firstname: " . htmlspecialchars($row["FIRSTNAME"]). 
        "</td><td>Lastname: " . htmlspecialchars($row["LASTNAME"]). 
        "</td></tr>";
    }
} 
else 
{
    echo "0 results";
}

I will keep on looking for a fix but I would be very grateful to anyone who could point out what I'm doing wrong. This would save me a lot of time so I can move forward with learning.