Connect to Database

Connect with MySQL Database
  • In this tutorial we can studed mysql database use two types.
  • 1.Mysqli
    • I. Mysqli(object-oriented
    • II. Mysqli(procedural)
  • 2.PDO
  • before 2012 PHP version 5 , php is used mysql exception after that php is used mysqli(in this mysqli, i means improved)and PDO(PHP Data Objects).
Which one is best MySQLi or PDO ?
  • Both MySQLi and PDO have their owen advantages so which one is best not decided.
  • MySQLi and PDO Both work on object-oriented, but in MySQLi also make a procedural API.
  • Both MySQLi and PDO are supported Prepared Statements. Prepared Statements protect from SQL injection. so both help to security of web application.
  • For Example of connect a MySQL Database

If run program in your local server like XAMPP, WAMPP, etc. so your server credentials like...

$servername= "localhost";
$username = "root";
$password= ""; (blank)

MySQLi Object-Oriented

<?php
$servername = "localhost";
$username = "username";
$password = "password";

// Create connection
$conn = new mysqli($servername, $username, $password);

// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}

echo "Connected successfully";
?>

MySQLi Procedural

<?php
$servername = "localhost";
$username = "username";
$password = "password";

// Create connection
$conn = mysqli_connect($servername, $username, $password);

// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}

echo "Connected successfully";
?>

PDO

<?php
$servername = "localhost";
$username = "username";
$password = "password";
try {
$conn = new PDO("mysql:host=$servername;dbname=student", $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();
}
?>

Close the Connection
  • In PHP connection will be close automatically when the script ends. but you are close the connection before the use below statement.


//MySQLi Object-Oriented:
$conn->close();

//MySQLi Procedural:
mysqli_close($conn);

//PDO:
$conn = null;