使用php进行基本的mysql数据提取

I've looked all over here. Please be patient as I am new to php and mysql. I got WAMPP installed & seems to be working OK. I created a simple "test" database from phpMyAdmin and "firsttable" in that. I can do a simple connect using example from w3schools, but trying to select & display data I entered only throws back errors.

<?php
$servername = "localhost";
$username = "root";
$password = "";

// Connect
$conn = mysqli_connect($servername, $username, $password);

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

$sql = "SELECT reference, firstname, lastname, room FROM firsttable";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
    // output data of each row
    while($row = $result->fetch_assoc()) {
        echo "id: " . $row["reference"]. " - Name: " . $row["firstname"]. " " . $row["lastname"]. "room:" . $row["room"]. "<br>";
    }
} else {
    echo "0 results";
}


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

First off, I get a parse error on line 17. The one that reads:

if ($result->num_rows > 0) {

The error says: Trying to get property of non-object.

I tried wrapping the whole php code in tags and saving it as html, but then it appeared that no row data was ever found.

I am able to use very simple code that connects successfully. I can confirm the database is in there, so is the table, and the contents I added to it.

Please, what am I doing wrong?

You need to specify the database when you connect:

$database = 'test';

$conn = mysqli_connect($servername, $username, $password, $database);

where $database is the name of your database (test in this case). MySQL doesn't know which database your table resides in without you telling it.

In addition, you should always include error checking for your database connection (you have two of these, you don't need the last one) as well as any queries. Sans this, you can check your error logs for more information when something fails.