0

First of all I know that it might be a duplicate question but I did some search for example this question but I couldn't understand how it works.

I have this code...

<?php
$host       = "localhost";
$user       = "root";
$pass       = "Passw0rd";
$database   = "test";

$db = new PDO("mysql:host={$host};dbname={$database}", $user, $pass);
$stmt = $db->prepare("SELECT * FROM patient WHERE fname LIKE :q OR lname LIKE :q");
$stmt->bindValue(':q', '%'.$_GET['q'].'%');
$stmt->execute();

while ( $row = $stmt->fetch() ) {
    echo '<a href="members2.php?view=' . $row->id . '" target="_blank">' . $row->fname . ' ' . $row->lname . '</a><br/>';
}
?>

And I get this error

Trying to get property of non-object in E:\xampp\htdocs\ptixiaki\livesearch.php on line 13

Line 13 is this line ...

echo '<a href="members2.php?view=' . $row->id . '" target="_blank">' . $row->fname . ' ' . $row->lname . '</a><br/>';

Can you help me to fix that

Community
  • 1
  • 1
Waaaaat
  • 634
  • 3
  • 14
  • 29
  • 5
    You may want to use `fetchObject()` instead of `fetch()`, otherwise you get an array, and not an object. – Clément Malet Apr 08 '15 at 15:24
  • @ClémentMalet Thank you it fixed something but now I get this `Notice: Undefined property: stdClass::$id in E:\xampp\htdocs\ptixiaki\livesearch.php on line 13` – Waaaaat Apr 08 '15 at 15:26
  • Try `$result = $sth->fetch(PDO::FETCH_BOTH);print_r($result);` to see what is the result returned. – A l w a y s S u n n y Apr 08 '15 at 15:27
  • @ClémentMalet I fixed the second error . Write your first comment as an answer in order to accept it – Waaaaat Apr 08 '15 at 15:28
  • 1
    As @ClémentMalet said using `fetchObject()` allows you to do this `$row->id` and with `fetch()` you can do this `$row['id']` – Fares M. Apr 08 '15 at 15:29

1 Answers1

3

You have to use fetchObject() instead of a regular fetch() to specify that you want to treat the row as an object (and use its properties), and not as an array.

Clément Malet
  • 5,062
  • 3
  • 29
  • 48