[SOLVED] The Answer in Here Class query PDO property of non-object
I get this error when trying to display the record using while.
Notice: Trying to get property of non-object in "$contacts[] = $obj;
and this my code
public function selectAll($connect,$order) {
if ( !isset($order) ) {
$order = "name";
}
$dbIdO=$this->anti_injection($order);
$dbres =$connect->prepare("SELECT * FROM contacts ORDER BY '".$dbIdO."' ASC");
$dbres->execute();
$contacts = array();
while ($obj = $dbres->fetchAll(PDO::FETCH_ASSOC) != NULL ) {
$contacts[] = $obj;
}
return $contacts;
}
The connection code
<?php
class ContactsService {
private $contactsGateway = NULL;
var $myconn;
public function openDb() {
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "sample";
$myconn;
try{
$conn = new PDO("mysql:host=$servername;dbname=$dbname",$username,$password);
//ser the pdo error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
echo "Connect Successfully";
$this->myconn = $conn;
}
catch(PDOException $e)
{
echo "Connection failed: " . $e->getMessage();
}
return $this->myconn;
}
private function closeDb() {
$this->myconn = null;
}
public function __construct() {
$this->contactsGateway = new ContactsGateway();
}
public function getAllContacts($order) {
try {
$this->openDb();
$connect = $this->myconn;
$res = $this->contactsGateway->selectAll($connect,$order);
$this->closeDb();
return $res;
} catch (Exception $e) {
$this->closeDb();
throw $e;
}
}
public function getContact($id) {
try {
$this->openDb();
$res = $this->contactsGateway->selectById($id);
$this->closeDb();
return $res;
} catch (Exception $e) {
$this->closeDb();
throw $e;
}
return $this->contactsGateway->find($id);
}
private function validateContactParams( $name, $phone, $email, $address ) {
$errors = array();
if ( !isset($name) || empty($name) ) {
$errors[] = 'Name is required';
}
if ( empty($errors) ) {
return;
}
throw new ValidationException($errors);
}
public function createNewContact( $name, $phone, $email, $address ) {
try {
$this->openDb();
$this->validateContactParams($name, $phone, $email, $address);
$res = $this->contactsGateway->insert($name, $phone, $email, $address);
$this->closeDb();
return $res;
} catch (Exception $e) {
$this->closeDb();
throw $e;
}
}
public function deleteContact( $id ) {
try {
$this->openDb();
$res = $this->contactsGateway->delete($id);
$this->closeDb();
} catch (Exception $e) {
$this->closeDb();
throw $e;
}
}
}
?>
normally when i return the while use mysqli, this query work. but when i change to pdo i not get the result just the notice.