PHP - Connecting to the database via PHP Data Objects (PDO)


To connect to the database, keep the credentials - the user and password - separated from the code in a configuration file.

We already have this file as config/app.json.

Let's add the correct credentials for our database.

 "db": { 
   "user": "root", 
   "password": "" 

You usually specify other information related to the connection, such as the host, port, or name of the database.

To connect to the database, instantiate an object from the PDO class.

The constructor of this class expects three arguments:

  • Data Source Name (DSN), which is a string that represents the type of database to use;
  • the name of the user; and
  • the password.

We have the username and password from the Config class, but we still need to build DSN.

One of the formats for MySQL databases is <database type>:host=<host>;dbname=<schema name>.

As our database system is MySQL, it runs on the same server, and the schema name is bookstore, DSN will be mysql:host=;dbname=bookstore.

$dbConfig = Config::getInstance()->get('db'); 
$db = new PDO( 

Related Topic