【发布时间】:2011-10-08 01:59:48
【问题描述】:
我的 Web 应用程序目前确实执行简单的查询:简单的 CRUD 操作、计数、...
几个月前,有人推荐我在这里为此编写一个简单的 PDO 包装器(以避免每次执行查询时都编写 try/catch、prepare()、execute() 等)。展示了这个示例方法(我做了一些更改,以便可以在我自己的项目中使用它):
public function execute() {
$args = func_get_args();
$query = array_shift($args);
$result = false;
try {
$res = $this->pdo->prepare($query);
$result = $res->execute($args);
} catch (PDOException $e) { echo $e->getMessage(); }
return $result;
}
由于我需要执行更多操作(执行查询、检索 1 条记录、检索多条记录、计算结果),我为所有这些创建了一个方法:
public function getMultipleRecords() {
$args = func_get_args();
$query = array_shift($args);
$records = array();
try {
$res = $this->pdo->prepare($query);
$res->execute($args);
$records = $res->fetchAll();
} catch (PDOException $e) { echo $e->getMessage(); }
return $records;
}
public function getSingleRecord() {
$args = func_get_args();
$query = array_shift($args);
$record = array();
try {
$res = $this->pdo->prepare($query);
$res->execute($args);
$record = $res->fetch();
} catch (PDOException $e) { echo $e->getMessage(); }
return $record;
}
public function execute() {
$args = func_get_args();
$query = array_shift($args);
$result = false;
try {
$res = $this->pdo->prepare($query);
$result = $res->execute($args);
} catch (PDOException $e) { echo $e->getMessage(); }
return $result;
}
public function count() {
$args = func_get_args();
$query = array_shift($args);
$result = -1;
try {
$res = $this->pdo->prepare($query);
$res->execute($args);
$result = $res->fetchColumn();
} catch(PDOException $e) { echo $e->getMessage(); }
return $result;
}
如您所见,大部分代码是相同的。每个方法只有两行代码不同:$result 的初始化(我总是想返回一个值,即使查询失败)和获取。除了使用 4 种方法,我可以只编写其中一种并传递一个带有动作类型的额外参数。这样,我可以使用一堆 if/else 语句的 switch 语句。但是,我认为代码可能会变得混乱。这是解决这个问题的好方法吗?如果没有,有什么好的解决方法?
我遇到的第二个问题(这就是我现在正在研究这门课的原因)是我想将准备好的语句与 LIMIT SQL 语句一起使用。但是,这是不可能的:
$res = $pdo->prepare("SELECT * FROM table LIMIT ?");
$res->execute(array($int));
变量将因某种原因被引用(因此查询将失败),如下所述: https://bugs.php.net/bug.php?id=40740
解决方案似乎使用了 bindValue() 并使用 int 数据类型作为参数: http://www.php.net/manual/de/pdostatement.bindvalue.php
我可以重写方法来支持这一点,但我还需要使用一个额外的参数。我不能再只使用$db->execute($sql, $variable1, $variable2);,因为我需要知道数据类型。
解决这个问题的最佳方法是什么?
谢谢
【问题讨论】: