试图获取非对象的属性

试图获取非对象的属性

This question already has answers here:
mysqli_fetch_assoc() expects parameter / Call to a member function bind_param() errors. How to get the actual mysql error and fix it?
                                
                                    (2个答案)
                                
                        
                                5个月前关闭。
            
                    
有人可以帮助我更正此代码吗?

我不断收到此错误:


  注意:试图获取非对象的属性“ num_rows”


<?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>";
    }
  }

?>

最佳答案

更改

if ($result->num_rows > 0) {




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


然后它将起作用。

编辑:它不会炸毁的原因是,首先,您要查看是否有任何结果。如果没有,它将不会尝试显示它们(这是发生错误的地方)。

你真的应该更换

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




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


然后使用prepared statements。但这是另一个问题。

关于php - 试图获取非对象的属性'num_rows',我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/50002520/

10-10 06:05