Database Techniques and PHP - Inside a row array (
Page 3 of 4 )
Just what are these rows that are being returned? By default, they’re indexed arrays, where the positions in the array correspond to the order of the columns in the returned result. For example:
$row = $result->fetchRow();
if (DB::isError($row)) {
die($row->getMessage());
}
var_dump($row);
array(3) {
[0]=>
string(5) "Foundation"
[1]=>
string(4) "1951"
[2]=>
string(12) "Isaac Asimov"
}
You can pass a mode parameter to fetchRow() or fetchInto() to control the format of the row array. The default behavior, shown previously, is specified with DB_FETCHMODE_ORDERED.
The fetch mode
DB_FETCHMODE_ASSOC
creates an array whose keys are the column names and whose values are the values from those columns:
$row = $result->fetchRow(DB_FETCHMODE_ASSOC)
;
if (DB::isError($row)) {
die($row->getMessage());
}
var_dump($row);
array(3) {
["title"]=>
string(5) "Foundation"
["pub_year"]=>
string(4) "1951"
["name"]=>
string(12) "Isaac Asimov"
}
The DB_FETCHMODE_OBJECT mode turns the row into an object with a property for each column in the result row:
$row = $result->fetchRow(DB_FETCHMODE_ASSOC)
;
if (DB::isError($row)) {
die($row->getMessage());
}
var_dump($row);
object(stdClass)(3) {
["title"]=>
string(5) "Foundation"
["pub_year"]=>
string(4) "1951"
["name"]=>
string(12) "Isaac Asimov"
}
To access data in the object, use the $object->property notation:
echo "{$row->title} was published in {$row->pub_year} and was written by {$row-> name}";
Foundation was published in 1951 and was written by Isaac Asimov
Finishing the result
A query result object typically holds all the rows returned by the query. This may consume a lot of memory. To return the memory consumed by the result of a query to the operating system, use the free() method:
$result->free();
This is not strictly necessary, as
free()
is automatically called on all queries when the PHP script ends.
Disconnecting
To force PHP to disconnect from the database, use the disconnect() method on the database object:
$db->disconnect();
This too is not strictly necessary, however, as all database connections are discon
nected when the PHP script ends.