1

My code returns the following error:

Notice: Trying to get property 'message' of non-object in C:\xampp\htdocs\mysqlsample.php on line 11

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';
}
?>
u_mulder
  • 54,101
  • 5
  • 48
  • 64
  • Try `echo $r['message']` if that does work and you'd like to use a object instead of an array try to use `fetchAll()` – Yvan Watchman Mar 24 '18 at 19:19
  • There are hundreds of questions/answers on this already, and searching here (and Google) will surely give you enough to go on to find the solution? not being unhelpful, but much better when you can search and solve things yourself. – James Mar 24 '18 at 19:20
  • 1
    Possible duplicate of [Reference - What does this error mean in PHP?](https://stackoverflow.com/questions/12769982/reference-what-does-this-error-mean-in-php) – James Mar 24 '18 at 19:20

4 Answers4

3

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.

James
  • 4,644
  • 5
  • 37
  • 48
0

You're using $query->fetch() which returns an array, yet you're using it as an object $r->message. Either use it as an array $r['message'], or if you prefer to use objects then change to $query->fetchObject()

Alvarez
  • 1,303
  • 1
  • 10
  • 28
0

You can use fetch and get an object, but you haven't done it yet. 2 ways:

//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
V.Rangelov
  • 29
  • 6
0

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.
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()
Read PHP Manual for further info