下面是我的PDO包装器。我希望能够使用run
方法,但是希望能够检查执行是否成功,例如:
if($sth->execute())
{
...
}
但是,正如您在包装器中看到的那样,run命令仅返回prepare
语句,最有效的方法是什么?
<?php
class Database {
const hostname = 'localhost';
const user = 'root';
const password = '';
const charset = 'utf8';
const database = 'syn_v2';
protected static $instance;
protected $pdo;
protected function __construct()
{
$opt = array(
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_OBJ,
PDO::ATTR_EMULATE_PREPARES => false
);
$dsn = sprintf('mysql:host=%s;dbname=%s;charset=%s', self::hostname, self::database, self::charset);
$this->pdo = new PDO($dsn, self::user, self::password);
}
public static function instance()
{
if(self::$instance === null)
{
self::$instance = new self;
}
return self::$instance;
}
public function __call($method, $args)
{
return call_user_func_array(array($this->pdo, $method), $args);
}
public function run($sql, $args = [])
{
if(!$args)
{
return $this->query($sql);
}
$stmt = $this->pdo->prepare($sql);
$stmt->execute($args);
return $stmt;
}
}
?>
答案 0 :(得分:1)
由于PDOStatement::execute
返回true / false,并且您当前的run
方法成功返回PDOStatement
,因此我将成功返回PDOStatement
,否则返回false。
/**
* @return PDOStatement|false
*/
public function run($sql, $args = [])
{
if (!$args) {
return $this->pdo->query($sql);
}
if ($stmt = $this->pdo->prepare($sql)) {
if ($stmt->execute($args)) {
return $stmt;
}
}
return false; //either prepare or execute failed
}