occupation
Also for the sake of this tutorial, we use a database server at IP address
10.0.0.1, running MySQL, with username ubuntu and password
alm65z. You need to replace these details with your own; use localhost
for connecting to the local server.
The first step to using PEAR::DB is to include the standard PEAR::DB file,
DB.php. Your PHP will be configured to look inside the PEAR directory for
include() files, so you do not need to provide any directory information.
PEAR::DB is object oriented, and you specify your connection details at the
same time as you create the initial DB object. This is done using a URL-like
system that specifies the database server type, username, password, server,
and database name all in one. After you have specified the database server
here, everything else is abstracted, meaning you only need to change the
connection line to port your code to another database server.
This script in Listing 47.6 connects to our server and prints a status message.
LISTING 47.6 Connecting to a Database Through PEAR::DB
Click here to view code image
<?php
include("DB.php");
$dsn = "mysql://ubuntu:[email protected]/dentists";
$conn = DB::connect($dsn);
if (DB::isError($conn)) {
echo $conn->getMessage() . "\n";
} else {
echo "Connected successfully!\n";
}
?>
You should be able to see how the connection string breaks down. It is server
name first, then a username and password separated by a colon, then an @
symbol followed by the IP address to which to connect, and then a slash and
the database name. Notice how the call to connect is DB::connect(),
which calls PEAR::DB directly and returns a database connection object for
storage in $conn. The variable name $dsn was used for the connection
details because it is a common acronym that stands for data source name.
If DB::connect() successfully connects to a server, it returns a database
object you can use to run SQL queries. If not, you get an error returned that