尝试 PDO 包装器并在数据库中存在记录时获得'NULL'结果



我刚刚尝试了 https://phpdelusions.net/pdo/pdo_wrapper 的PDO包装器。

首先是PDO包装器

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;
}
}

然后是用户类

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

然后实例化类用户

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

有一条与 ID = 3 关联的记录,但我得到的结果是 NULL,为什么?

如注释中所述,find 方法不返回任何内容,它可能将其存储在$this->data中,但永远不会返回。

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

最新更新