[已解决]这里的答案 Class query PDO property of non-object
尝试使用while时显示记录时出现此错误。
Notice: Trying to get property of non-object in "$contacts[] = $obj;
这是我的代码
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;
}
连接代码
<?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;
}
}
}
?>
通常当我使用mysqli返回while时,此查询工作正常。但是当我改为pdo时,我没有得到通知的结果。
答案 0 :(得分:-1)
这个问题不是真的。
$contacts[] = $obj;
行无法引发Notice: Trying to get property of non-object
错误,因为此行中没有涉及任何属性。
您的代码中没有[可见]语法错误。
最有可能没有SQL错误,好像有任何错误,应该引发异常,但它不是。
除此之外,您的订单将永远不会以您期望的方式运作。您应该根据白名单对其进行过滤,而不是引用字段名称,如here
所示此外,您编写的循环永远不会以您期望的方式返回数据。努力做到这一点&#34;正确&#34;你真的把它弄坏了。你想要写的是
while ($obj = $dbres->fetch(PDO::FETCH_ASSOC)) {
$contacts[] = $obj;
}
你真正需要的是
$contacts = $dbres->fetchAll(PDO::FETCH_ASSOC);