How to Connect MySQL Database Server Using PHP

PHP Functions to Connect to MySQL Database

In many PHP Application, you have to connect MySQL database to access and manipulate the data. In the older version of the PHP, developers used the mysql_connect function to connect Mysql database. But the function is the deprecated function from PHP5.5 and you cannot use it in anymore your PHP projects.

However, you can use two alternative functions to connect to MySQL database. These two functions are Mysqli_connect() and pdo(). In mysqli, i stands for improved and PDO stands for PHP Data Objects.

Which Function is Suitable for Database connection

If you want to access data from the MySQL database, you can use both mysqli and PDO. The mysqli supports only MySQL database while PDO() support more than twelve different types of databases.

How to Connect MySQL Database Server Using PHP

If you are developing an application and want to switch to another database you should use PDO(). But in future if you have decided not to use the database other than MySQL you can use mysqli. The mysqli_connect provides the easiest way of connecting and executing queries using PHP.

The mysqli provides both object-oriented and procedure oriented API to access and use MySQL database. So, its a better option for any developer to access and manipulate MySQL database.

How to Connect MySQL database

In order to connect to MySQL database, you can use both mysqli and PDO. The PDO supports only object-oriented API while mysqli provides both object-oriented and procedural oriented API to connect to the database. Below are the syntaxes you can use in your projects.

Connect MySQL Database Using mysqli Procedural

Connect MySQL Database Using mysqli Object-Oriented

Connect MySQL Database Using PDO

Close MySQL Database connection

The connection to MySQL database will be closed automatically after the execution of the script end. However, you can close the connection before the script end using the.mysqli_close()

mysqli_connect Procedural

mysqli_connect Object-Oriented

Using PDO

Example to Connect to MySQL Database(Using Mysqli procedural)

Below is the simple example to explain the MySQL connection in your localhost. Localhost in your local server requires you to put hostname as localhost, username as root and a blank password. You can use this in your localhost computer running Wamp or Xamp server with MySQL.