0

I want to ask why am I getting this error:

Trying to get property 'num_rows' of non-object

with the following code:

$sql = "SELECT * FROM $table_name ORDER BY Author";
$result = $mysqli->query($sql);
if ($result->num_rows > 0) {...

I have used echo $sql to look if the problem lies there, but there is no problem. My SQL looks fine.

I have tried to use Prepared Statements and got other errors too.

The line which gives the error is the one with the if statement.

Any ideas?

Mikhail Kholodkov
  • 23,642
  • 17
  • 61
  • 78
  • 1
    The query failed use error reporting to see why. – user3783243 Jun 21 '18 at 18:56
  • Check for [mysqli errors](http://php.net/manual/en/mysqli.error.php) after your query to find out why it failed. I'm guessing there may be something wrong with `$table_name`, or that table doesn't have a column Author. – aynber Jun 21 '18 at 18:57
  • 1
    A prepared statement wouldn't actually help you here because you can't bind table names. – user3783243 Jun 21 '18 at 18:59
  • You can try var_dump($result); and check If this is an object. Probably it's a mysql error. Try mysql_error() to see what is it. – Luma Macagnan Jun 21 '18 at 19:13
  • 2
    @lumadev They'll need http://php.net/manual/en/mysqli.error.php `mysql_` wont work with `mysqli`. – user3783243 Jun 21 '18 at 19:16

1 Answers1

1

This is a better (non-error checking) pattern to follow IMO:

$sql = "SELECT * FROM $table_name ORDER BY Author";
$result = $mysqli->query($sql);
if (!empty($result)) {

You should also consider using PDO

user3783243
  • 5,368
  • 5
  • 22
  • 41
TrophyGeek
  • 5,902
  • 2
  • 36
  • 33
  • Why is this better? Isn't this just bypassing the problem and the OP will never get results? – user3783243 Jun 21 '18 at 19:05
  • Yes, non-error-checking. It's better IMO because it handles lots common failure cases in php and is readable. If the call returns `false`, or `null`, or an empty string `''` or and empty array `[]` all can be handled by `empty()` correctly. – TrophyGeek Jun 21 '18 at 22:19