繁体   English   中英

我正在尝试获取非对象的属性值

[英]I'm trying to get a property value of a non-object

这听起来像是重复的,但是我在这里搜索了与此相关的所有主题,但还是没有运气... :(

我有以下代码:

$result = array();

include 'conn.php';
$sql = "SELECT * FROM editlistm WHERE checkvou IN (SELECT checkvou FROM editlist)";
$result = $conn->query($sql);
//$numRows = $result->count($rs);   
$numRows = $result->num_rows;


if ($numRows > 0) {
// output data of each row
    while($row = $result->fetch_object()) {
        array_push($items, $row);
    }
    echo json_encode($items);
} 

conn.php:

$servername = "localhost";
$username = "root";
$password = "";
$dbase = "cadacctg";

// Create connection 
$conn = new mysqli($servername, $username, $password, $dbase);

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

我没有发现任何错误,但一直在说:

'试图在第11行的C:...中获取非对象的属性'($ numRows = $ result-> num_rows;)

为什么它不被视为对象? 我该怎么办? 提前致谢 :)

使用fetch_objectfetch_array获取字段值。

var_dump($result) before $numRows = $result->num_rows;

如果为假,则查询中存在问题

问题是,此代码:

$result = $conn->query($sql);

可能会失败。

http://php.net/manual/en/mysqli.query.php#refsect1-mysqli.query-returnvalues

失败时返回FALSE。 对于成功的SELECT,SHOW,DESCRIBE或EXPLAIN查询,mysqli_query()将返回mysqli_result对象。 对于其他成功的查询,mysqli_query()将返回TRUE。

因此,您需要对其进行检查,例如:

$result = $conn->query($sql);

// For SELECT query, check if it's false
if (!$result) {
    exit('Query has failed.');
}

检查您的值正确无误:

if ($result = $conn->query($sql)) {
     ///value returns not-false,
     $numRows = $result->num_rows; 
     ... 
}
else {
     //there is a problem with your SQL
}

如果->query正常运行,这只会为$numRows返回非布尔值-负值。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM