Norman
Norman

Reputation: 6365

How to use column names in PHP PDO without binding columns

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.

Upvotes: 0

Views: 166

Answers (2)

Phil
Phil

Reputation: 165069

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.

Upvotes: 3

Sina R.
Sina R.

Reputation: 1788

You can use this code:

extract($row);

and then you have:

$name, $address, etc.

Upvotes: 0

Related Questions