Creating a Connect Instance
With all of PEAR, the MDB2 package, and the MySQL driver installed, you can start to take advantage of these new additions. But to do so, you need to understand what MDB2 is providing you with: a layer of abstraction.
In other words, MDB2 knows everything about accessing any major brand of database program you may have installed. You simply use a common set of commands and tell MDB2 which database to access. This means you can migrate to another SQL database such as PostgreSQL and will only have to install the new MDB2 driver and change a single line of code in your PHP file to be up and running again.
You connect to a MySQL database using MDB2 with code such as the
following, where $db_username
and the
other $db_
variables have already
been read in from the login.php
file:
require_once 'MDB2.php'; $dsn = "$db_username:$db_password@$db_hostname/$db_database"; $mdb2 = MDB2::connect("mysql://$dsn");
The require_once
line loads
MDB2. In the next line, the variable $dsn
stands for data source
name and is an identifier for the database. It comprises
username:password@hostname/database. The
variable $mdb2
is an object returned
by calling the connect
method within the MDB2
class. Recall that as mentioned in Chapter 5, the double colon (::
) token indicates a class to be used on the
left and a method to call from that class to the right.
The full string passed to the connect method is as follows:
mysql://username:password@hostname/database
The mysql:// at the head of ...
Get Learning PHP, MySQL, and JavaScript now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.