试图获取非对象的属性"num_rows" [英] Trying to get property 'num_rows' of non-object

查看:166
本文介绍了试图获取非对象的属性"num_rows"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人可以帮助我更正此代码吗?

Could someone help me to correct this code?

我不断收到此错误:-

注意:尝试获取非对象的属性'num_rows'

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

?>

推荐答案

更改

if ($result->num_rows > 0) {

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

然后它将起作用.

编辑:之所以不会崩溃,是因为首先您要查看是否有任何结果.如果没有,它将不会尝试显示它们(这是发生错误的地方).

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).

您真的应该替换

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

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

,然后使用 准备好的声明 .但这是另一个问题.

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

这篇关于试图获取非对象的属性"num_rows"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆