How To Connect MySQL Database With PHP

By bhagwatchouhan
How To Connect MySQL Database With PHP

In this tutorial, we will learn how to use PHP to connect to MySQL database for database operations. This tutorial provides the possibles ways to connect to MySQL using MySQLi Extension and PDO.

 

MySQLi Extension

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

Connect using themysqli extension in a proceduralway

We have to use the function mysqli_connect in order to open a 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 an 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 approaches.

Share this blog:

Profile picture for user bhagwatchouhan
bhagwatchouhan