就个人而言,我更喜欢使用所有PDO的包装功能,简化了所需的代码大增。
例如,运行势必查询(当然,我所有的查询),我这样做:
$iterable_resultset = query("INSERT INTO accounts (username, email, password) VALUES (:username, :email, :password)", array(':username'=>'bob', ':email'=>'[email protected]', ':password'=>'bobpassword'));
注意,不仅是sql只是一个字符串,但它实际上是一个可重复使用的字符串,如您可以简单地将sql作为字符串传递,并更改要传入的变量数组(如果要在后面执行类似的插入操作)(不适用于此情况,但适用于其他sql用例)。
,我用它来创建此包装函数的代码如下:
/**
* Run bound queries on the database.
*
* Use: query('select all from players limit :count', array('count'=>10));
* Or: query('select all from players limit :count', array('count'=>array(10, PDO::PARAM_INT)));
*
* Note that it returns foreachable resultset object unless an array is specifically requested.
**/
function query($sql, $bindings=array(), $return_resultset=true) {
DatabaseConnection::getInstance(); // Gets a singleton database connection
$statement = DatabaseConnection::$pdo->prepare($sql); // Get your pdo instance, in this case I use a static singleton instance. You may want to do something simpler.
foreach ($bindings as $binding => $value) {
if (is_array($value)) {
$first = reset($value);
$last = end($value);
// Cast the bindings when something to cast to was sent in.
$statement->bindParam($binding, $first, $last);
} else {
$statement->bindValue($binding, $value);
}
}
$statement->execute();
if ($return_resultset) {
return $statement; // Returns a foreachable resultset
} else {
// Otherwise returns all the data an associative array.
return $statement->fetchAll(PDO::FETCH_ASSOC);
}
}
// Wrapper to explicitly & simply get a multi-dimensional array.
function query_array($sql_query, $bindings=array()) {
return query($sql_query, $bindings, false); // Set return_resultset to false to return the array.
}
正如评论指出的是,你要使用自己的方法建立一个数据库连接,并得到一个初始化pdo,但通常它允许你的绑定sql被减少到只有一行。
for assoc_array支持?你不是指指定的占位符吗? – 2011-04-16 03:10:37
只是好奇,你会用这种方式吗?没有帮手功能等? – 2011-04-16 03:22:28
我今天才刚刚开始使用PDO,如果您愿意解释,我不知道辅助函数是什么? – Basic 2011-04-16 03:42:12