MySQL, MySQLi & PDO Connection Using PHP Script

MySQL, MySQLi & PDO Connection Using PHP Script

MySQL have the following general format with PHP functions –

mysql_function(value,value,...);

Example of opening a Connection: 1) MySQL

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

// Create connection
$con = mysql_connect($servername, $username, $password);

// Check connection
if (mysql_connect_error()) {
die("Database connection failed: " . mysql_connect_error());
}
echo "Database Connected successfully";
?>

2) MySQLi Object-Oriented

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

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

// Check connection
if (mysqli_connect_error()) {
die("Database connection failed: " . mysqli_connect_error());
}
echo "Database Connected successfully";
?>

3) MySQLi Procedural

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

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

// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully";
?>

4) PDO

 <?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();
}
?>

PDO require a valid database to connect, otherwise it will throw an exception. We can also create a database with mysql, mysqli while creating a connection

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

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

// Check connection
if (!$con) {
die("Connection failed: " . mysqli_connect_error());
}
echo "Databas creted successfully";
?>

Close the Connection 1)MySql:

         mysql_close($con);

2) MySQLi Object-Oriented:

 $con->close(); 

3) MySQLi Procedural:

 mysqli_close($con); 

4)PDO

 $con = null; 
Post a Comment