Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/redis/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 试图获得财产';消息';非对象_Php - Fatal编程技术网

Php 试图获得财产';消息';非对象

Php 试图获得财产';消息';非对象,php,Php,我的代码返回以下错误: 注意:试图在第11行的C:\xampp\htdocs\mysqlsample.php中获取非对象的属性“message” 我需要做什么改变才能让它工作 <?php try { $handler = new PDO('mysql:host=127.0.0.1;dbname=group_projectdb','root',''); } catch (Exception $e) { echo $e->getMessage(); die()

我的代码返回以下错误:

注意:试图在第11行的C:\xampp\htdocs\mysqlsample.php中获取非对象的属性“message”

我需要做什么改变才能让它工作

<?php 

try {
    $handler = new PDO('mysql:host=127.0.0.1;dbname=group_projectdb','root','');
} catch (Exception $e) {
    echo $e->getMessage();
    die();
}
$query = $handler->query('SELECT * FROM security');
while ($r = $query->fetch()) {
    echo $r->message,'<br';
}
?>

错误提示您正在访问非对象,请尝试:

echo $r['message'];

PDOStatement::fetch()
检索关联数组或编号数组中的结果,或两者都检索。

您使用的是返回数组的
$query->fetch()
,但您将其用作对象
$r->message

可以将其用作数组
$r['message']
,或者如果您更喜欢使用对象,请更改为
$query->fetchObject()

您可以使用fetch并获取对象,但您还没有这样做。2种方式:

//如果你这次需要的话

while ($r = $query->fetch(PDO::FETCH_OBJ)) {
//如果您每次或大多数时候都将其用作对象

try {
    $handler = new PDO('mysql:host=127.0.0.1;dbname=group_projectdb','root','');
    $handler->setAttribute(PDO::FETCH_OBJ);
} ...
//rest is the same, you use $query->fetch() and get an object

您试图使用$r->message作为对象获取值,但在获取记录时未设置获取模式。
如果您希望以对象形式获取值,则必须在对象中设置获取模式。
通过使用$query->fetch(PDO::fetch_OBJ)或$query->fetchObject()
阅读
要了解更多信息,请尝试
echo$r['message']
如果这样做有效,并且您希望使用对象而不是数组,请尝试使用
fetchAll()
关于此问题已有数百个问题/答案,在这里搜索(和谷歌)肯定会给您足够的时间来找到解决方案?不是没有帮助,而是当你可以自己搜索和解决问题时会更好。可能是重复的