具有更好参数放置的PDO库

时间:2012-10-02 08:02:09

标签: php pdo

不要误解我PDO很棒,但我不喜欢它,是变量如何远离它们属于SQL语句的位置。意思是我有一个类似的查询:

$stmt = $dbh->prepare("SELECT * FROM users WHERE email = ? AND pass = ?");

替换?的变量总是远离以下几行:

$stmt->bindParam(1, $email);
$stmt->bindParam(2, $pass);

如果你有很多参数,这可能会非常难看。使用:email代替?并不会让事情变得更好。有时您会在同一个方法中将参数视为数组,如:

$db->query("SELECT * FROM users WHERE email = ? AND pass = ?",
   array($email, $pass));

稍微好一些,但有10个变量仍然很难看。实际上,您只创建一次变量?。此伪变量也不支持代码突出显示。

我认为像这样更好

$db->prepare("SELECT * FROM user WHERE email = ", $email, " AND pass = ", $pass);

您甚至可以像这样包含binParam()的参数:

$db->prepare_new(
   "SELECT * FROM user WHERE email = ", array($email, PDO::PARAM_STR),
   " AND pass = ", $pass);

如果有一个支持这种风格的库,我会更聪明。你知道吗?

3 个答案:

答案 0 :(得分:1)

拥有?:email的重点是您可以多次重复使用该查询。例如:

$stmt = $pdo->prepare("SELECT true FROM user WHERE email = :email");
$stmt->execute(array($email1));
$stmt->execute(array($email2));
// etc.

在查询中包含特定变量会完全删除此功能。

如果您愿意,您可以随时扩展或组成PDO:

class DB {
   private $pdo;

   public function executeQuery($query, $args) {
      $stmt = $this->pdo->prepare($query);
      $stmt->execute($args);
   }
}
$db->executeQuery("SELECT true FROM user WHERE email = :email", array($email1));

这隐藏了您不喜欢的PDO功能。

更新:

这是一种不寻常的做事方式,但它似乎是你所追求的:

$pdo->query("SELECT true FROM user WHERE email = " . $pdo->quote($email));

http://us2.php.net/manual/en/pdo.quote.php

答案 1 :(得分:1)

如果每个偶数参数都是参数,你可以这样做:

class MyPDO extends PDO {
    public function prepareQuery() {
        $query_str = "";
        $params = array();
        foreach(func_get_args() as $key => $param) {
            if( $key % 2 == 0 ) {
                $query_str .= $param;
            }
            else {
                $params[] = $param;
                $query_str .= ' ? ';
            }
        }

        $prepared = $this->prepare($query_str);
        foreach( $params as $key => $param ) {
            $prepared->bindParam( $key+1, $param );
        }
        return $prepared;
    }
}

然后你可以按照自己的意愿使用它:

$db = new MyPDO( .. );
$db->prepareQuery("SELECT * FROM user WHERE email = ", $email, " AND pass = ", $pass);

PS:未经测试 - 只是一个概念

答案 2 :(得分:0)

您可以将类似的添加到函数中:

$stmt = $dbh->prepare("SELECT * FROM users WHERE email = :email AND pass = :pass");

$arr = array(
    'email' => 'test@test.com',
    'pass' => 'secret'
);

foreach($arr as $key => $val){
    $stmt->bindParam(':'.$key, $val);

}

示例:

function myBindParams($stmt, $bindings){
     foreach($bindings as $key => $val){
        $stmt->bindParam(':'.$key, $val);
     }
     return $stmt;
}


$stmt = $dbh->prepare("SELECT * FROM users WHERE email = :email AND pass = :pass");

$arr = array(
    'email' => 'test@test.com',
    'pass' => 'secret'
);

$stmt = myBindParams($stmt, $arr);