0

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.

6
  • 2
    Please don't delete your previous questions only to ask the same thing again Commented Oct 4, 2013 at 5:12
  • @Ben The answer may very well lie in this comment Commented Oct 4, 2013 at 5:21
  • I just love magic fancy quotes, they're just Oh so fancy... and destructive. Commented Oct 4, 2013 at 5:23
  • Downvote because: 1. Access to array members has absolutely nothing to do with PDO. 2. The question itself is a mere whim. Keeping your data in array is cleaner and preferable. 3. It seems the OP have no idea on templates, which should be his first and foremost concern. Commented Oct 4, 2013 at 6:17
  • @YourCommonSense Fair enough, though I'm usually pro-education and against punishment.. Commented Oct 4, 2013 at 6:27

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

No, I think it is. It both answers the question and clearly outlines why it's a bad idea. Great answer actually :)
0

You can use this code:

extract($row);

and then you have:

$name, $address, etc.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.