Explains all the steps required to connect MySQL database using PHP for database operations.

How To Connect MySQL Database With PHP
How To Connect MySQL Database With PHP
May 15, 2019

In this tutorial, we will learn how to connect MySQL database using PHP to perform database operations.

MySQLi Extension

MySQLi works only with MySQL database. It supports both procedural API and object-oriented in order to work with MySQL.

Connect using the mysqli extension in procedural way

We have to use the function mysqli_connect in order to open connection with MySQL server as shown below. We must also handle the error in case the connection is not established between PHP and MySQL.

<?php
$hostname = "localhost";
$username = "username";
$password = "password";
$dbname = "database";

// Create Connection
$conn = mysqli_connect( $hostname, $username, $password );

// Test Connection
if( !$conn ) {

// Print error
die( "Failed to connect: " . mysqli_connect_error() );
}

echo "Connected successfully";

// Switch database
mysqli_select_db( $conn, $dbname );

// Perform database operations

// Close the connection
mysqli_close( $conn );

Make sure to replace the database username, database password, and database name.

Connected using the object-oriented approach

We can also connect to MySQL in the object-oriented approach using mysqli as shown below.

<?php
$hostname = "localhost";
$username = "username";
$password = "password";
$dbname = "database";

// Create Connection
$conn = mysqli( $hostname, $username, $password, $dbname );

// Test Connection
if( $conn->connect_error ) {

// Print error
die( "Failed to connect: (" . $conn->connect_errno . ") - " . $conn->connect_error );
}

echo "Connected successfully - " . $mysqli->host_info . "\n";

// Perform database operations

// Close the connection
$conn->close();

PDO - PHP Data Objects

PDO works with several standard database systems including MySQL, Microsoft SQL Server, Oracle Database using object-oriented approach. In case only standard SQL queries are used, it's very easy to switch between the different database systems using PDO.

We can connect to the database system using PDO as shown below.

<?php
$hostname = "localhost";
$username = "username";
$password = "password";
$dbname = "database";

try {

$conn = new PDO( "mysql:host=$hostname;dbname=$dbname", $username, $password );

// Configure PDO error mode
$conn->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );

echo "Connected successfully";
}
catch( PDOException $e ) {

echo "Failed to connect: " . $e->getMessage();
}

// Perform database operations

// Close the connection
$conn = null;

Also, replace the database name, database password, and database username with the actual one.

This is how we can connect with MySQL using PHP in both procedural way and object-oriented approach.

Write a Comment

Click on the captcha image to get new code.
Discussion Forum by DISQUS