0

我收到一个似乎发生不正确的错误。

我在不同的班级中已经足够接近相同的功能,但似乎没有发生。我正在使用的功能是:

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 错误?

4

2 回答 2

-1

尝试这个。
这不会导致任何错误。

<?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();

}
于 2013-07-20T21:27:29.060 回答
-2

我认为 PHP 正在抱怨这一行:

$query->execute($params);

因为$queryis 不在 if else 子句之外声明。另一种可能性是一个查询错误,所以在$query之后Falseprepare()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();
}
于 2013-07-20T21:31:31.750 回答