Web Info and IT Lessons Blog...

Wednesday, 11 February 2015

MySql Database Connection in PHP

The previous lesson of PHP Lessons Series was about How to get ip address of user in PHP and in this lesson we will learn to connect to a MySql database in PHP.

MySql Database Connection in PHP

In this lesson we will connect to a MySql database using three different methods i.e

1. Connect to MySql database using simple mysql extension.
2. Connect to MySql database using mysqli extension.
3. Connect to MySql database using PDO.

How to connect to a MySql database using mysql extension?

We can easily connect to a MySql database using the PHP code given below:



$dbhost = "localhost";
$dbusername = "root";
$dbpass = "";
$dbname = "testdb";

$connection = mysql_connect("$dbhost","$dbusername","$dbpass");
if($connection){
 echo "Database Connection Successful.";
 if(mysql_select_db($dbname)){
  echo 'Database Selected Successfully.';
 }else{
  echo 'Database does not exist.';
 }
}else{
 echo "Error Connecting to Database.";
}


In the above code we have made mysql connection and then selected a database named "testdb" from our databases.

How to connect to a MySql database using mysqli extension?

MSQLI is basically improved version of MySQl and it automatically comes with installation of PHP 5. A sample code of connection to a mysql database using mysqli extension is given below:



$dbhost = "localhost";
$dbusername = "root";
$dbpass = "";
$dbname = "testdb";

$connection = mysqli_connect($dbhost, $dbusername, $dbpass);
if($connection){
 echo "Database Connection Successful.";
 if(mysqli_select_db($connection,$dbname)){
  echo 'Database Selected Successfully.';
 }else{
  echo 'Database does not exist.';
 } 
}else{
 echo "Error Connecting to Database.";
}


How to connect to a MySql database using PDO?

A sample code of connection to a mysql database using PDO is given below:



$dbhost = "localhost";
$dbusername = "root";
$dbpass = "";
$dbname = "testdb";

try 
{
    $connection = new PDO("mysql:host=$dbhost;dbname=$dbname", 
    $dbusername, $dbpass);
    $connection->setAttribute(PDO::ATTR_ERRMODE, 
    PDO::ERRMODE_EXCEPTION);
    echo "Database Connection Successful.";
}
catch(PDOException $e)
{
    echo "Connection Error: " . $e->getMessage();
}


The above code is used to make myql database connection and throws an error exception when the connection fails.

No comments:

Post a Comment