如何在不绑定列的情况下在PHP PDO中使用列名 [英] How to use column names in PHP PDO without binding columns
问题描述
使用php pdo和mySql而不是使用$row[‘columnName’]
时,是否存在一种在不绑定列的情况下直接输出数据时使用列名的方法.
Is there a method to directly use the name of the column when outputting data without binding columns when using php pdo and mySql, instead of using $row[‘columnName’]
.
例如:我当前的方法
$sql = "select id, name, address, country from members where country = :country";
$stmt=$conn->prepare($sql);
$stmt->execute(array(':country' => $country));
while( $row = $stmt->fetch() ) { //I can forgo the while loop.
echo $row[‘name’]; //Can I use $name here?
echo $row[‘address’];
echo $row[‘country’];
}
不是使用$row[‘colName’]
,而是可以以某种方式使用$colName
本身吗?我知道ezSql
就是这样,但是我不使用ezSql
,因为它不支持预备语句.如何才能做到这一点?也许使用for each
?有可能吗?
Instead of using $row[‘colName’]
, is it possible to somehow use $colName
itself? I know ezSql
does it this way, but I’m not using ezSql
since it does not support prepared statements. How can this be done? Maybe using for each
? Is it possible?
我知道我可以绑定列,但是我也试图避免这种情况.保持代码最少.
I know I can bind columns, but I'm trying to avoid that too. Keep code at a minimum.
推荐答案
如果您真的不想绑定列或使用数组引用或对象属性,并且不介意污染当前变量范围,请尝试使用此丑陋的技巧
If you really don't want to bind columns or use array references or object properties and don't mind polluting the current variable scope, try this ugly hack
while( $row = $stmt->fetch(PDO::FETCH_ASSOC) ) {
extract($row);
echo $name;
// etc
}
正如我在您的上一个重复的问题的答案中所提到的,PDOStatement::bindColumn
是更可取的.除了证明自己不专业之外,我真的不知道您试图通过将代码保持在最低限度" 来实现什么.
As mentioned in my answer on your previous, duplicate question, PDOStatement::bindColumn
would be preferable. I really don't know what you're trying to achieve by "keeping code to a minimum" other than prove yourself unprofessional.
这篇关于如何在不绑定列的情况下在PHP PDO中使用列名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!