Viewed   94 times

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.

 Answers

5

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.

Friday, November 25, 2022
 
nagul
 
5

PDO does not escape the variables. The variables and the SQL command are transferred independently over the MySQL connection. And the SQL tokenizer (parser) never looks at the values. Values are just copied verbatim into the database storage without the possibility of ever causing any harm. That's why there is no need to marshall the data with prepared statements.

Note that this is mostly a speed advantage. With mysql_real_escape_string() you first marshall your variables in PHP, then send an inefficient SQL command to the server, which has to costly segregate the actual SQL command from the values again. That's why it's often said that the security advantage is only implicit, not the primary reason for using PDO.

If you concat the SQL command and don't actually use prepared statments (not good!), then yes, there still is an escape function for PDO: $pdo->quote($string)

Saturday, November 5, 2022
5

There are many duplicated questions but all answers are beyond any reason, offering complicated solutions involving running extra queries etc.

While the solution is right here: when using fetchAll(), you already have all the column headers in the $result variable

$headerNames = $result ? array_keys($result[0]) : [];

now you can foreach over $coulmnNames to get the table header and the foreach over $result to display the results.

<table class='table'>
  <tr>
  <?php foreach($coulmnNames as $name): ?>
    <th><?= $name ?></th>
  <?php endforeach ?>
  </tr>
  <?php foreach($result as $row){ ?>
    <tr class="table-row">
      <?php foreach($result as $value){ ?>
        <td><?= $value ?></td>
    </tr>
  <?php endforeach ?>
</table>
Friday, August 12, 2022
 
wirus
 
5

Well, at second glance your question looks more complex to be answered with just one link

How does php pdo's prepared statements prevent sql injection?

How can prepared statements protect from SQL injection attacks?

What are other pros/cons of using PDO?

Most interesting question.
A greatest PDO disadvantage is: it is peddled and propagated a silver bullet, another idol to worship.
While without understanding it will do no good at all, like any other tool.
PDO has some key features like

  • Database abstraction. It's a myth, as it doesn't alter the SQL syntax itself. And you simply can't use mysql autoincremented ids with Postgre. Not to mention the fact that switching database drivers is not among frequent developer's decisions.
  • Placeholders support, implementing native prepared statements or emulating them. Good approach but very limited one. There are lack of necessary placeholder types, like identifier or SET placeholder.
  • a helper method to get all the records into array without writing a loop. Only one. When you need at least 4 to make your work sensible and less boring.

Does using PDO reduce efficiency?

Again, it is not PDO, but prepared statements that reduces efficiency. It depends on the network latency between the db server and your application but you may count it negligible for the most real world cases.

Monday, September 5, 2022
2

I take that back looks like you can use the cursor orientation contants to select the result... sample code coming... I havent tried this so you may need to play a bit. This is also based on the assumption that a PDO::FETCH_ORI_FIRST acts like a data_seek and leaves the cursor on the first position as opposed to returning it to whatever it was before.

$stmt = $pdo->prepare('SELECT id FROM table', array(PDO::ATTR_CURSOR => PDO::CURSOR_SCROLL));
$stmt->execute();

$first = $pdo->fetch(PDO::FETCH_ASSOC, PDO::FETCH_ORI_FIRST);
$first_row = $first['id'];

// other stuff

// first iteration we rewind to the first record;
$cursor = PDO::FETCH_ORI_FIRST;

while (false !== ($row = $stmt->fetch(PDO::FETCH_ASSOC, $cursor))) {
   $id = $row['id'];
   // successive iterations we hit the "next" record
   $cursor = PDO::FETCH_ORI_NEXT; 
   echo $id;
}

I dont think you can rewind a statement... Assuming these blocks arent seprated by a bunch of intermediary logic id just do it in the loop.

$STH->setFetchMode(PDO::FETCH_COLUMN); // no need to pull an array
$count = 0;
while ($id = $STH->fetch()) {      
  if($count === 0) {
   $first_row = $id;
  }
  echo $id;
  $count++;
}
Tuesday, October 18, 2022
Only authorized users can answer the search term. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :