Database Abstraction with PEAR - DB::connect
(Page 3 of 7 )
mixed connect (string $dsn [, array $options]) |
That is our connect function. It is what we will use to connect to the database. Its actual use will look something like:
$db = DB::connect("mysql://user:pass@host/db_name", FALSE); |
It will return a connection object or an error object which will be stored in $db. You may be wondering what that wierd :: is. Well, DB is the class for data abstraction and connect is the function. Normally you would see it look like DB->connect(). The reason for the :: is so that we can use the connect function without creating an instance of the class DB. Maybe a little bit different than you are used to, but it has its uses. The :: can also be used to access a function of a base class when you are dealing with inherited classes.
You can see that we passed the connect function what sort of looks like a URL. This is a dsn, or data source name. Here you pass it the database type and other connection information such as username and password. Here is a list of supported database types:mysql -> MySQLpgsql -> PostgreSQLibase -> InterBasemsql -> Mini SQLmssql -> Microsoft SQL Serveroci8 -> Oracle 7/8/8iodbc -> ODBC (Open Database Connectivity)sybase -> SyBaseifx -> Informixfbsql -> FrontBase
The second, optional parameter is whether to use persistent connections or not. Not all databases support persistent connections and the default for this parameter is false.
Here is how it is commonly used:
<?php require_once 'DB.php';
$user = 'foo'; $pass = 'bar'; $host = 'localhost'; $db_name = 'clients_db';
$dsn = "mysql://$user:$pass@$host/$db_name";
$db = DB::connect($dsn, false); ?> |
Next: DB::disconnect >>
More Database Articles Articles
More By Matt Wade