Trying PDO wrapper and getting result as 'NULL' when there is a record present in the database [duplicate]

点点圈 提交于 2020-02-29 10:00:11

问题


I just tried a PDO wrapper from https://phpdelusions.net/pdo/pdo_wrapper.

First the PDO Wrapper

class MyPDO
{
    protected static $instance;
    protected $pdo;

    public function __construct() {
        $opt  = array(
            PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
            PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_OBJ,
            PDO::ATTR_EMULATE_PREPARES   => FALSE,
        );
        $dsn = 'mysql:host='.DB_HOST.';dbname='.DB_NAME.';charset='.DB_CHAR;
        $this->pdo = new PDO($dsn, DB_USER, DB_PASS, $opt);

    }

    // a classical static method to make it universally available
    public static function instance()
    {
        if (self::$instance === null)
        {
            self::$instance = new self;
        }
        return self::$instance;
    }

    // a proxy to native PDO methods
    public function __call($method, $args)
    {
        return call_user_func_array(array($this->pdo, $method), $args);
    }

    // a helper function to run prepared statements smoothly
    public function run($sql, $args = [])
    {
        if (!$args)
        {
            return $this->query($sql);
        }
        $stmt = $this->pdo->prepare($sql);
        $stmt->execute($args);
        return $stmt;
    }
}

and then the user class

class User
{
    /* @var MyPDO */
    protected $db;

    protected $data;

    public function __construct()
    {
        $this->db = MyPDO::instance();
    }

    public function find($id)
    {
        $this->data = $this->db->run("SELECT * FROM user_account WHERE id = ?", [$id])->fetch();

    }
}

and then instantiate class user

$user = new User();
$a = $user->find(3);

var_dump($a);

There is a record associated with ID = 3 but the result I get is NULL, why?


回答1:


As mentioned in the comments, the find method doesn't return anything, it is probably storing it just fine in $this->data but is never returned.

public function find($id)
{
    $this->data = $this->db->run("SELECT * FROM user_account WHERE id = ?", [$id])->fetch();
    return $this->data;
}


来源:https://stackoverflow.com/questions/59985559/trying-pdo-wrapper-and-getting-result-as-null-when-there-is-a-record-present-i

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!