如何识别这是一个非对象在代码中,如果它显示错误为“试图获得非对象的属性”


how to identify which is a non-object in the code if it shows error as `trying to get property of non-object`?

在对现有脚本进行了一些修改后,我创建了一个错误:

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

我试图找出如何识别变量$result是否是一个对象,所以我没有得到这个错误(我在这个特定的行if ($result-> num_rows > 0) {上得到错误)。

<?php 
$sql = "SELECT * FROM input WHERE id =".$_GET["id"]; 
$result = mysqli_query ($conn,$sql);
if ($result-> num_rows > 0) { 
    while($row -> $result->fetch_assoc()) { 
        $myid = $row["id"] ;
        $sql2 = "SELECT * FROM output WHERE question_id = $myid ORDER BY date DESC";
        $result2 = $conn->query($sql2);
        $sql3 = "SELECT COUNT(*) as rowCount FROM output WHERE question_id = '".$myid."'";
        $result3 = $conn->query($sql3);
        $rowCount= $result3->fetch_assoc();
?>

我如何事先知道这是否是一个对象?

首先,您是否在此之前的代码中初始化了变量$conn ?
其次,你想让while循环像这样:
while($row = $result->fetch_assoc()) { ... }

你可以使用数组或对象来查找内容:

is_object() to find object 
is_array() to find array 
$sql = "SELECT * FROM compt WHERE id =1"; 
$result = mysqli_query ($conn,$sql);
if ($result->num_rows > 0) { 
    while($row = $result->fetch_assoc()) { 
    }
    }