I'm converting some code to access a database to PDO. I've come across the following:
mysql_data_seek($result, 0);
$row0 = mysql_fetch_assoc($result);
And from my readings on Google etc, I understand this should be:
$row0 = $result->fetch(PDO::FETCH_ASSOC, PDO::FETCH_ORI_ABS, 0);
however this isn't working. Any ideas what i'm doing wrong?
From manual;
Fetches a row from a result set associated with a PDOStatement object. The fetch_style parameter determines how PDO returns the row.
You need a stmt
that was created by PDO::prepare
method.
Let's see this;
// assuming $pdo was created before as well
$sth = $pdo->prepare("SELECT name, colour FROM fruit");
// exec here
$sth->execute();
// get a row here
$row = $sth->fetch(PDO::FETCH_ASSOC);
// here probably you'll get a print out like
// Array([name] => Banana, [color] => Yellow)
print_r($row);
See more details here: PHP PDOStatement::fetch
First option with query:
You can iterate query
result directly..
foreach ($db->query($sql) as $row) {
echo $row['FirstName'];
}
Second option with execute:
$sth = $db->prepare($sql);
$sth->execute();
$row = $sth->fetch(PDO::FETCH_ASSOC); // fetch the next row from statement
echo $row['FirstName'];