Connect PHP with MySQL database

While developing dynamic website, first thing we need to connect our database to PHP application. Even small application which requires dynamic data needs a database connection. Without database connection, we can't perform any operations like create, read, update and delete.

In this tutorial, we will connect our PHP application with MySQL database using MySQLi and PDO easily with practical example.

Before starting, we need to create database into MySQL. It doesn't matter you are using XAMPP or WAMPP for development. Open phpmyadmin or use terminal to create database.

In PHP, there are two ways to connect MySQL database : MySQLi and PDO. We will cover them one by one in further tutorial.

MySQLi Database Connection In PHP

MySQLi stands for MySQL Improved. MySQLi is relational database driver which provides interface with MySQL database. MySQLi provides both ways for procedural and object-oriented.

MySQLi gives you prepared statements - a safer way of sending data to MySQL and protecting you from SQL injection.

Let's take example to connect database into PHP with MySQLi object oriented.

The above code will print output based on your serve name, user name and password. It will print success message if connected to database otherwise it will show error logs.

Let's take another example for same with Procedural way.

In above code, we use mysqli_connect() function to establish connection and check it's connected or not. Lastly we will clost connection using mysqli_close() function.

PDO Database Connection In PHP

The PDO stands for PHP Data Object. The major advantage of PDO is it works with 12 different database systems whereas MySQLi only works with MySQL databases.

In this example, we will connect to specific database using PDO connection.

To create PDO object it requires three parameter first one is DNS(Data Source Name), second is user name and last one is password.

In above code, we have tried to connection into try and catch block. It will try to run code of try block and it any type of errors occurs then it will print error message or handle error using catch block's code. Here, we are simply printing message for connection.

At last, we are closing connection by setting connection object null.


Here, We have learned to connect MySQL database using MySQLi and PDO and closed it. There may be common errors like username and password errors. So make sure user name, password, and database name before implementation.

Share your thoughts

Ask anything about this examples