MySQL PHP – Connected to MySQL Database but Cannot Print Data

MySQLPHP

I connected successfully to my database and the I tried to print my data but I can only see the "Connected succesfully" line in the browser. Here is my code:

<?php 

$db=@mysqli_connect("host","root","pass");
if (!db) { die('Cannot connect with the database.');}

// Check connection
if ($db->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";

$sql = "SELECT username FROM students";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
    // output data of each row
    while($row = $result->fetch_assoc()) {
        echo "username: " . $row["username"].  "<br>";
    }
} else {
    echo "0 results";
}
$conn->close();



?>

Best Answer

You definitely have to check your query execution response, as clearly suggested by the mysqli::query documentation, by adding the following code fragment just after the query call.

if (!$result) {
    printf("Error: [%s] %s<br/>", $conn->errno, $conn->error);
}

Hope it helps.

Related Question