How to use column names in PHP PDO without binding columns

故事扮演 提交于 2020-02-02 16:21:23

问题


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’].

Eg: My current method

$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’];
}

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.


回答1:


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
}

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.




回答2:


You can use this code:

extract($row);

and then you have:

$name, $address, etc.



来源:https://stackoverflow.com/questions/19173673/how-to-use-column-names-in-php-pdo-without-binding-columns

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!