<?php
$db = new PDO('sqlite::memory:');
$db->exec("CREATE TABLE fruit (name VARCHAR(100), colour VARCHAR(100))");
$db->exec("INSERT INTO fruit (name, colour) VALUES
('apple', 'red'),
('banana', 'yellow'),
('orange', 'orange'),
('kiwi', 'green')");
$sth = $db->prepare("SELECT name, colour FROM fruit");
$sth->execute();
/* Exercise PDOStatement::fetch styles */
echo "PDO::FETCH_ASSOC: ";
echo "Return next row as an array indexed by column name\n";
$result = $sth->fetch(PDO::FETCH_ASSOC);
var_dump($result);
echo "\n";
echo "PDO::FETCH_BOTH: ";
echo "Return next row as an array indexed by both column name and number\n";
$result = $sth->fetch(PDO::FETCH_BOTH);
var_dump($result);
echo "\n";
echo "PDO::FETCH_LAZY: ";
echo "Return next row as a PDORow object with column names as properties\n";
$result = $sth->fetch(PDO::FETCH_LAZY);
var_dump($result);
echo "\n";
echo "PDO::FETCH_OBJ: ";
echo "Return next row as an stdClass object with column names as properties\n";
$result = $sth->fetch(PDO::FETCH_OBJ);
var_dump($result);
echo "\n";
?>
The above example will output:
PDO::FETCH_ASSOC: Return next row as an array indexed by column name
array(2) {
["name"]=>
string(5) "apple"
["colour"]=>
string(3) "red"
}
PDO::FETCH_BOTH: Return next row as an array indexed by both column name and number
array(4) {
["name"]=>
string(6) "banana"
[0]=>
string(6) "banana"
["colour"]=>
string(6) "yellow"
[1]=>
string(6) "yellow"
}
PDO::FETCH_LAZY: Return next row as a PDORow object with column names as properties
object(PDORow)#3 (3) {
["queryString"]=>
string(30) "SELECT name, colour FROM fruit"
["name"]=>
string(6) "orange"
["colour"]=>
string(6) "orange"
}
PDO::FETCH_OBJ: Return next row as an stdClass object with column names as properties
object(stdClass)#4 (2) {
["name"]=>
string(4) "kiwi"
["colour"]=>
string(5) "green"
}