Databases and PHP - Data Source Names (
Page 4 of 4 )
A data source name (DSN) is a string that specifies where the database is located, what kind of database it is, the username and password to use when connecting to the database, and more. The components of a DSN in PEAR are assembled into a URL-like string:
type(dbsyntax)://username:password@protocol+hostspec/ database
The only mandatory field is
type
, which specifies the PHP database backend to use. Table 8-1 lists the implemented database types at the time of writing.
Table 8-1. PHP database types
| Name |
Database |
|
Mysql |
MySQL |
| mysqli |
MySQL (for MySQL >= 4.1) |
| Pgsql |
PostgreSQL |
| Ibase |
InterBase |
| Msql |
Mini SQL |
| Mssql |
Microsoft SQL Server |
| oci8 |
Oracle 7/8/8i |
| Odbc |
ODBC |
| Sybase |
SyBase |
| Ifx |
Informix |
| Fbsql |
FrontBase |
| Dbase |
DBase |
| Sqlite |
SQLite |
The
protocol
is the communication protocol to use. The two common values are
"tcp"
and
"unix
,
"
corresponding to Internet and Unix domain sockets. Not every database backend supports every communications protocol.
These are some sample valid data source names:
mysql:///library
mysql://localhost/library
mysql://librarian@localhost/library
mysql://librarian@tcp+localhost/library
mysql:// librarian:passw0rd@localhost/library
In Example 8-1, we connected to the MySQL database
library
with the username
librarian
and password
passw0rd
.
A common development technique is to store the DSN in a PHP file and include that file in every page that requires database connectivity. Doing this means that if the information changes, you don’t have to change every page. In a more sophisticated settings file, you might even switch DSNs based on whether the application is running in development or deployment mode.
Please check back next week for the continuation of this article.