Hacking Google Maps and Google Earth (ExtremeTech)

(Dana P.) #1

Chapter 5 — Storing and Sharing Information 87


With PDO, you create a new object that provides connectivity to the RDBMS you are using,
rather than the implied database connectivity supported through the older interface. You must,
therefore, specifically create a new database connection object, as shown in Listing 5-22.


Listing 5-22:Connecting to a Database through PHP Data Objects
(PDO)

<?php


try {
$dbh = new PDO(‘mysql:host=localhost;dbname=google_maps’,’maps’,’maps’);
} catch (PDOException $e) {
print “Error!: “. $e->getMessage(). “
”;
die();
}


//Do your stuff


$dbh = null;


?>


Executing a query through the PDO method uses the exec()method to the database handle
that was created (that is,$dbh->exec()).


Populating the Database


Populating an RDBMS with SQL relies on composing a suitable INSERTstatement and then
using the database interface to execute that statement in the database. To insert data into a
table according to order of fields as they are created, you use a statement like the one shown in
Listing 5-23.


Listing 5-23: Inserting the Data

insert into restaurants(0,-0.6391666,52.911111,”China Inn”);


The zero for the ID is used to indicate that a new unique ID, automatically generated by the
database (according to the table definition), should be used for this value.


To execute the SQL statement with a Perl/DBI interface, use the code in Listing 5-24; for
traditional PHP, use Listing 5-25; and for PHP/PDO, use Listing 5-26.

Free download pdf