Chris Paton Chris Paton - 2 months ago 8
MySQL Question

Selecting Data from MySQL to PHP page

I another issue with MySQL (if you were following my last post I have decided to scrap inputting and focus on selecting for now).

I have been following a youtube tutorial on how to display data from my database on my php page. The following code is EXACTLY what he has given me.

However I'm sure the problem lies somewhere in connecting to the database, because if I remove everything other than that the connection code I still get the same problem.

When I load the page it just goes blank.

On Youtube when he loads the page he gets his results.

I've gone over my username, password and DB name 100 times and they are correct.

Can anyone see any problems with the following code?

<!DOCTYPE html>
<html>
<head>
</head>
<body>

<?php

$servername = "localhost";
$username = "cbdadmin";
$password = "XXXX";
$dbName = "cbd_players";

//create connection

$conn = new mysqli($servername, $username, $password, $dbName);

// check connection

if (conn -> connect_error) {
die ("connection failed: " . $conn -> connect_error);
}

$sql = "SELECT * FROM 'results'";

$result = $conn ->query($sql);

if ($result-> unm_rows > 0) {
echo "<table> <tr><th>Home Team</tr></th> <tr><th>Home Score</tr></th> <tr><th>Away Score</tr></th> <tr><th>Awa Team</tr></th> <tr><th>Venue</tr></th>";
while($row = $result -> fetch_assoc()){
echo "<tr><td>" . $row["hometeam"] . "</td> <td>" . $row["homescore"] . "</td> <td>" . $row["awayteam"] . "</td> <td>" . $row["awayscore"] . "</td> <td>" . $row["venue"] . "</td></tr>";
}

echo "</table>";

}

else {
echo "No game have yet been played.";
}

$conn->close();


?>

<p>Test</p>
</body>
</html>

Answer

Your code contains a few syntax errors.

This part of your code:

if (conn -> connect_error) {
    die ("connection failed: " . $conn -> connect_error);
}

$sql = "SELECT * FROM 'results'";

$result = $conn ->query($sql);

if ($result-> unm_rows > 0) {

and I will explain.

The single quotes around your table ' either need to be removed or use backticks, since they are not the right identifier qualifiers:

Then your if (conn -> with the missing $ in front of conn would have thrown an undefined constant conn notice using error reporting.

The unm_rows is a typo which should have read as num_rows.

Check for errors on the query also: