有了更多信息,我可以为您制作更完整的示例...
$params['calories'] = 150;
$params['colour'] = 'red';
$stmt = $dbh->prepare('SELECT name, colour, calories
FROM fruit
WHERE calories < :calories AND colour = :colour');
bindColumns($stmt,$params);
$stmt->execute();
function bindColumns(&$stmt, $params)
{
foreach($params as $key => $value)
{
$stmt->bindValue(":$key", $value);
}
}
快速说明:
* bindParam()需要通过引用获取其值
* bindValue()不需要
好吧......所以绑定后:
$params = array('name','color','calories');
$stmt = $dbh->prepare('SELECT name, color, calories FROM fruit');
$stmt->execute();
foreach($params as $index => $name) {
$stmt->bindColumn("$name", $$name);
}
while ($row = $stmt->fetch(PDO::FETCH_BOUND)) {
print $name . "\t" . $color . "\t\t" . $calories . "<br/>";
}
这使用称为变量变量的东西来制作动态变量名称($$name
)......几乎就像extract()
函数一样。问题是......如果我将其foreach($params...
放入它自己的函数中,它们就会丢失在该函数的范围内。唯一的选择是使它们成为一个数组,然后通过引用传入或返回。如果你这样做了,你会使用print $return_params['name']
什么的。
$stmt = $dbh->prepare('SELECT name, color, calories FROM fruit');
$success = $stmt->execute();
$return = bindColumnsAfterSelect($stmt, $params);
while ($row = $stmt->fetch(PDO::FETCH_BOUND)) {
print $return['name'] . "\t" . $return['color'] . "\t\t" . $return['calories'] . "<br/>";
}
function bindColumnsAfterSelect(&$stmt, $params)
{
$return = array();
foreach($params as $index => $name) {
$stmt->bindColumn("$name", $return[$name]);
}
return $return;
}
而且...您不需要将所有内容都命名为相同...您可以这样做:
$params = array('name'=>'fruit_name','color'=>'fruit_color','calories'=>'fruit_calories');
然后...
foreach($params as $table_name => $variable_name) {
$stmt->bindColumn("$table_name", $$variable_name);
}
Annnnnnd ...我并没有真正使用 PDO,所以我不确定你到底在做什么,但是这个 SO 帖子对你来说可能是一个更简单的选择?不知道。这是该页面的代码示例:
while( $row = $stmt->fetch(PDO::FETCH_ASSOC) ) {
extract($row);
echo $name;
// etc
}
再次编辑:这就是你想要的......但我真的,真的,真的不会这样做。
$stmt = $dbh->prepare('SELECT name, color, calories FROM fruit');
$success = $stmt->execute();
$return = bindColumnsAfterSelect();
eval($return); // this is a bad function to use like this.
// it does what you want but... it's just not right
// it's extremely powerful and shouldn't be used
// for things like this...
while ($row = $stmt->fetch(PDO::FETCH_BOUND)) {
print $name . "\t" . $color . "\t\t" . $calories . "<br/>";
}
function bindColumnsAfterSelect()
{
$x = '$stmt->bindColumn("name", $name);';
$x .= '$stmt->bindColumn("color", $color);';
$x .= '$stmt->bindColumn("calories", $calories);';
return $x;
}