0

So I am trying to work on this block of code for a personal project. This is an iteration of a sql query that is being passed by php.

1   $sql = "SELECT * FROM `table 1`";
2   $result = $conn->query($sql);
3
4   if ($result->num_rows > 0) {
5   // output data of each row
6   while($row = $result->fetch_assoc()) {
7   echo "id: " . $row["ID"]. " - Spell Name: " . $row["Spell Name"]. " - 
8   School " . $row["S"]. "<br>";
9   }
10  } else {
11  echo "0 results";
12  }
13  $conn->close();

When I run it, it gives

Notice: Trying to get property of non-object on line

I simply pulled this from the w3school tutorial, and replace the relevant column names. Just for the record, the dataset I am working with has roughly entries

  • What line is in the error message? – MCMXCII Dec 13 '17 at 17:52
  • The *actual* error message includes a line number. Go to that line of code. On that line of code you are trying to read a property from an object. That object isn't actually an object when the code executes. Go to where you *set* that object variable. That operation isn't doing what you think or is failing in some way. – David Dec 13 '17 at 17:55

2 Answers2

0

It would have helped to have the line number, but so far, it looks like $conn is not defined. You don't have a connection to the database.

Brac
  • 458
  • 4
  • 8
0

The only line in that code where you're accessing a property is $result->num_rows on line 4, which suggests that $result is not an object.

Assuming $conn is a PDO connection, it means PDO::query() is returning false, since that is the only non-object value it can return. If the connection object itself was invalid, you'd see a fatal error from line 2 when you run the query.

In turn, this suggests that your SQL is not executing correctly. Since your query is a simple SELECT * FROM... statement, the likely reason is that table 1 is either not a table, or is not accessible. Check by running the query against your database directly, using the MySQL command-line or similar.

iainn
  • 16,826
  • 9
  • 33
  • 40