我收到一个错误,似乎发生了错误。
我已经在不同的类中得到了足够多的相同函数,但它似乎没有发生。我使用的功能是:
public function UserInfo($type, $value) {
if($type == 'email') {
$query = $this->db->prepare("SELECT * FROM `accounts` where `provider` = '1' AND `email` = :value AND `type` = 'client' LIMIT 1");
} else {
$query = $this->db->prepare("SELECT * FROM `accounts` where `provider` = '2 'AND `prov_id` = :value AND `type` = 'client' LIMIT 1");
}
$params = array(":value" => $value,);
$query->execute($params);
return $query->FetchObject();
}
我正试图通过获取数据
$clients->UserInfo("id", $uid)->email;
PHP返回值,所以很明显对象确实存在,但它仍然抛出
PHP Notice: Trying to get property of non-object in /Users/Luke/public_html/manage.php on line 30
我使用的语法有问题吗,还是PHP错误?
试试这个
这不会导致任何错误。
<?php
class DB {
protected $db;
public function __construct() {
$this->db = PDO(
'mysql:dbname=test;host=127.0.0.1;charset=utf8',
'root',
''
);
$this->db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
public function UserInfo($type, $value) {
if ($type == 'email') {
$stmt = $this->db->prepare(
"SELECT * FROM `accounts` where `provider` = '1' AND `email` = ? AND `type` = 'client' LIMIT 1"
);
} else {
$stmt = $this->db->prepare(
"SELECT * FROM `accounts` where `provider` = '2 'AND `prov_id` = ? AND `type` = 'client' LIMIT 1"
);
}
$stmt->execute(array($value));
$result = $stmt->fetchObject();
if ($result === false) {
throw new Exception('value not found');
}
return $result;
}
}
try {
$clients = new DB;
echo $clients->UserInfo("id", $uid)->email;
} catch (Exception $e) {
echo $e->getMessage();
}
我认为PHP在抱怨这一行:
$query->execute($params);
因为CCD_ 3不是在if-else子句之外声明的。另一种可能性是一个查询错误,因此$query
是prepare()
之后的False
:http://php.net/manual/en/pdo.prepare.php
你能试试吗:
public function UserInfo($type, $value) {
$sql_query = '';
if($type == 'email') {
$sql_query = "SELECT * FROM `accounts` where `provider` = '1' AND `email` = :value AND `type` = 'client' LIMIT 1";
} else {
$sql_query = "SELECT * FROM `accounts` where `provider` = '2 'AND `prov_id` = :value AND `type` = 'client' LIMIT 1";
}
$query = $this->db->prepare($sql_query);
$params = array(":value" => $value,);
if ($query === false) return 'False query';
$query->execute($params);
return $query->FetchObject();
}