本文介绍了使用PDO的fetchAll帮助程序功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设我有一个函数
function fetchAll(){
$args = func_get_args();
$query = array_shift($args);
$query = str_replace("%s","'%s'",$query);
foreach ($args as $key => $val) {
$args[$key] = mysql_real_escape_string($val);
}
$query = vsprintf($query, $args);
if (!$query) return FALSE;
$res = mysql_query($query);
if (!$res) {
trigger_error("db: ".mysql_error()." in ".$query);
return FALSE;
}
$a = array();
while($row = mysql_fetch_assoc($res)) $a[]=$row;
return $a;
}
然后像这样使用它
$a=$db->fetchAll("SELECT * FROM users WHERE status=%s LIMIT %d,%d",$status,$start,$num);
如何使用PDO重写它?
我可以找到的每个示例都仅显示了如何直接绑定参数.我应该传递变量类型及其值吗?还是使此调用始终为4行-3个绑定并执行?
How can I rewrite it using PDO?
Every example I can find shows only how to bind parameters directly. Should I pass variable type as well as it's value? Or make this call always 4 lines - 3 binds and execute?
推荐答案
,显然,这(不再?)适用于LIMIT
子句.
edit: as the Colonel indicated, apparently this (no longer?) works with LIMIT
clauses.
如果您使用的是简单查询,则不必担心输入以下类型:
If you're using simple queries / are not that bothered with type:
function fetchAll(){
$args = func_get_args();
$query = array_shift($args);//'SELECT * FROM users WHERE status=? LIMIT ?,?'
//you'll need a reference to your PDO instance $pdo somewhere....
$stmt = $pdo->prepare($query);
$stmt->execute($args);
return $stmt->fetchAll();
}
这篇关于使用PDO的fetchAll帮助程序功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!