简体   繁体   English

试图获取非对象的属性“消息”

[英]Trying to get property 'message' of non-object

My code returns the following error: 我的代码返回以下错误:

Notice: Trying to get property 'message' of non-object in C:\\xampp\\htdocs\\mysqlsample.php on line 11 注意:尝试在第11行的C:\\ xampp \\ htdocs \\ mysqlsample.php中获取非对象的属性“消息”

What do I have to change to get it working? 为了让它正常工作,我需要改变什么?

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

As error says you're accessing non-object, try: 由于错误表示您正在访问非对象,请尝试:

echo $r['message'];

PDOStatement::fetch() retrieves results in an associative array or a numbered array, or both. PDOStatement::fetch()以关联数组或带编号的数组或两者检索结果。

You're using $query->fetch() which returns an array, yet you're using it as an object $r->message . 您正在使用$query->fetch()返回一个数组,但您将其用作对象$r->message Either use it as an array $r['message'] , or if you prefer to use objects then change to $query->fetchObject() 要么将它用作数组$r['message'] ,要么更喜欢使用对象,然后更改为$query->fetchObject()

You can use fetch and get an object, but you haven't done it yet. 你可以使用fetch并获取一个对象,但还没有完成。 2 ways: 2种方式:

//if you need it this time //如果你这次需要的话

while ($r = $query->fetch(PDO::FETCH_OBJ)) {

//if you will use this as object in general every time, or most of times //如果您每次或大部分时间都将此作为对象使用

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

You're trying to get value as a object by using $r->message but you didn't set the fetch mode while fetching the records. 您正在尝试使用$ r->消息将值作为对象获取,但在获取记录时未设置获取模式。
If you prefer to get value in object form then you have to set fetch mode in object 如果您希望以对象形式获取值,则必须在对象中设置获取模式
By using $query->fetch(PDO::FETCH_OBJ) or $query->fetchObject() 通过使用$ query-> fetch(PDO :: FETCH_OBJ)或$ query-> fetchObject()
Read PHP Manual for further info 阅读PHP手册以获取更多信息

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

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