86 Part I — Basics
The object created in the example,$dbh, now becomes the method for communicating with the
MySQL database. For example, to execute an arbitrary statement, you’d use the do()method.
Some examples of this are demonstrated later in this chapter.
Connecting to a Database with PHP
PHP provides built-in support for communicating with a number of different databases,
depending on how the application is compiled. MySQL support is usually included by default.
Older versions of PHP used a suite of built-in methods for communicating with a MySQL
database that were MySQL-specific. The interface has been improved since version 5.1, when
an object-based solution similar to the DBI solution in Perl was introduced.
For the older version, connecting to a database is a question of calling the mysql_connect()
function with the name of the host, username, and password. Once connected, you must select
the database to use before submitting any queries.
The old PHP method more or less mirrors the structure of connecting to a MySQL database by
hand through the command-line mysqltool and may make more sense to users familiar with
that tool.
An example of the typical connection sequence is shown in Listing 5-21.
Listing 5-21: Connecting to a Database through PHP (Traditional)
<?php
mysql_connect(localhost,’maps’,’maps’);
@mysql_select_db(‘google_maps’);
//Do your stuff
mysql_close();
?>
To execute a query through this interface, use the mysql_query()function.
PHP 5.1 supports an alternative method for communicating with a MySQL database or,
indeed, any database using the PHP Data Object (PDO) interface. The approach is similar in
style to the DBI approach used by Perl and is, therefore, more portable. However, it may take
some time for your hosting service to update to PHP 5.1. Check what version is supported
before choosing an interface type.