0

I'm brand new to the PDO syntax and I'm liking the learning curve! I'm refactoring code - migrating over from archaic mysqli_* methods.

Predictably, I've run into some snags, being a novice. One of the big ones is (forgive if this is a dumb question) retrieving data from the DB and echoing it out on the page. Here is what I have so far:

$getURLid = $_GET['id'];
$idQuery = $connection->prepare("SELECT * FROM pages WHERE page_id = :getURLid");
$idQuery->execute(array(':getURLid' => $getURLid));
$idRetrieved = $idQuery->fetchAll(); // This is the part I'm unclear on.

When I echo $idRetrieved['value'] to the page, nothing shows up. I'm missing something or misunderstanding how it works. Maybe fetchAll isn't what I should be using.

If it is, is a loop necessary to retrieve all rows? I was under the impression that fetchAll would loop through them automatically based on what I've read.

Thanks for the help.

Phil
  • 157,677
  • 23
  • 242
  • 245
gitlinggun
  • 108
  • 6

1 Answers1

2

Read the doco for PDOStatement::fetchAll closely. It returns an array of row data.

The type of data representing each row depends on your fetch mode which by default is PDO::FETCH_BOTH. This would mean each row is an array with both numeric and associative keys. If you're only going to access the data associatively, I'd recommend using PDO::FETCH_ASSOC, eg

$idRetrieved = $idQuery->fetchAll(PDO::FETCH_ASSOC);

You would then either need to loop or access each row via its index, eg

foreach ($idRetrieved as $row) {
    echo $row['value'];
}

// or

echo $idRetrieved[0]['value']; // assuming there's at least one row.
Phil
  • 157,677
  • 23
  • 242
  • 245