How to Connect to a MySQL Database Using PHP Data Objects (PDO)

PHP



In this article, we show how to connect to a MySQL database using PHP Data Objects (PDO).

PHP supports all the major relational databases used by large companies, including Oracle, IBM's DB2, and Microsoft's SQL server. It also serves open source databases, such as SQLite, PostgreSQL, and MySQL.

In this code, we specifically focus on how to connect to a MySQL database with PHP, specifically using PHP Data Objects (PDO).

PDO, PHP Data Objects extension, is a data-access abstraction layer. With PDO< you no longer need to use functions for specific databases. PDO is a consistent interface for multiple databases. With PDO, you no longer have to use the mysql_ functions or sqlite_ functions. Instead, you can simply use the PDO interface to work with all relational databases with the same code (with the same functxions). If you change databases, you'll only have to change the Data Source Name (DSN) of the PDO for the code to work.

So to access a MySQL database using a PDO, the code is shown below.



By running this code, you should be able to connect to a serve that hosts a MySQL database.

If you wanted to connect to another database, such as PostgreSQL or SQLite, then you would just need to change the data source name. Note that for PostgreSQL or SQLite, only the DSN is needed to connect to the database, not the username and password. For MySQL, the DSN, username, and password are needed to connect to the database.

For the DSN for PDO, there are 3 basic parts: the PDO driver name (such as mysql, sqlite, or pgsqul), a colon, and the driver-specific syntax. For MySQL, the host name and the database name are needed to connect to the database.


Related Resources

How to Connect to a PostgreSQL Database using PHP Data Objects



HTML Comment Box is loading comments...