PHP is commonly used in the world of web. PHP has many built in tools to connect with different drivers and in this tutorial we are going to use MySQL driver to connection between PHP and MySQL.
There is two to connect database in PHP 5 and later version.
- MySQLi extension
- PDO (PHP Data Obect)
As the name implies that MySQLi
i
stands for improved version of mysql php driver and mysqli only supports one database but in PHP PDO, its supports 12 databases.
Both Mysqli and PDO supports object oriented buy mysqli also supports procedural functions.
Connect php to mysql using PDO
Connection mysql to updo requires PDO extension, which you can install from official PHP website.
After installation of updo create a new file for connection.
<?php
$servername = "localhost";
$username = "username";
$password = "password";
try {
$conn = new PDO("mysql:host=$servername;dbname=myDB", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected successfully";
} catch(PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}
?>
Connect php to mysql using MySQLi
Most of the php comes with mysqli extension and no other installation required to connect the php using mysqli.
<?php
$servername = "localhost";
$username = "root";
$password = "";
$database = 'test'
// Create connection
$conn = new mysqli($servername, $username, $password,$database);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
?>
Close the Connection
The connection will be closed automatically when the script ends. To close the connection before, use the following:
MySQLi Object-Oriented:
$conn->close();