3

Could someone help me to correct this code?

I keep getting this error:-

Notice: Trying to get property 'num_rows' of non-object

<?php

  $test = $_GET['param'];
  $sql =" SELECT * FROM img WHERE id = $test ";
  $result = $conn->query($sql);

  if ($result->num_rows > 0) {
    // output data of each row
    while($row = $result->fetch_assoc()) {
      echo " <div class='col-lg-9'> ";

      echo " <div class=card mt-4> ";
      echo " <img src=http://placehold.it/900x400 class=img-responsive alt=Responsive image> ";
      echo " <div class='card-body'> ";
      echo " <a class=pull-right> <button type=button class='btn btn-primary'>Prezzo " .$row["prz"]. " €</button> </a> ";

      echo " <h3 class=card-title>" .$row["nome"]. "</h3> "  ;
      echo "<br>";
      echo "<br>";
      echo " <p class=card-text>" .$row["ldscr"]. "</p> ";
      echo "</div>";
      echo "</div>";
      echo "<br>";
    }
  } 

?>
Alive to die - Anant
  • 70,531
  • 10
  • 51
  • 98

3 Answers3

10

Change

if ($result->num_rows > 0) {

to

if (!empty($result) && $result->num_rows > 0) {

And then it will work.

EDIT: The reason it won't blow up is that first you are seeing if there are any results, first. If there are not, then it will not attempt to show them (this is where the error was occuring).

You really should replace

$sql =" SELECT * FROM img WHERE id = $test ";

with

$sql =" SELECT * FROM img WHERE id = ?";

and then use prepared statements. But that is another question.

Theodore R. Smith
  • 21,848
  • 12
  • 65
  • 91
0

I'm not sure if you have declared your connection. Check this documentation

$conn = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

if ($result = $conn->query("SELECT ....")) {

    /* determine number of rows result set */
    if($result->num_rows > 0)
    {
       //....with the data stuff
    }


    /* close result set */
    $result->close();
}

/* close connection */
$conn->close();
Chopi
  • 1,123
  • 1
  • 12
  • 23
0

As suggested here [http://php.net/manual/it/mysqli.query.php], I would do it this way:

if ($result = $conn->query($sql)) {
    while($row = $result->fetch_assoc()) {
        // ...
    }
} 

If a query call fails it returns FALSE