How to Connect to MySQL Database Using PHP ?

In this blog, we will discuss (How to Connect to MySQL Database Using PHP)
we will create a connection with MySql DB using 2 methods.

  • mysqli_connect
  • PDO
    We will discuss both connections in details and also discuss which connection more secure and more reliable after a successful connection,

Using mysqli_connect() :

PHP provides mysqli_connect() function to open a database connection. This function takes parameters and returns a MySQL link identifier on success or false on failure.

<?php
$dbservername="localhost";
$dbuser="root";
$dbpassword="";
$dbname="myblog";
$connection=mysqli_connect($dbservername,$dbuser,$dbpassword,$dbname);
if(! $connection ) {
            die('Could not connect:Error ' . mysql_error());
         }
         echo 'Connected successfully:Success';
         mysql_close($connection);
?>

2. Using PDO :

PDO refers to PHP Data Object, which is a PHP extension that defines a lightweight and consistent interface for accessing a database in PHP. It is a set of PHP extensions that provide a core PDO
class and database-specific driver.

There are 3 PDO classes,

PDO – PDO represents a connection between PHP and the database.
PDOStatement – PDOStatement represent the prepared statement and after the execution of the statement,
sets an associated result.
PDOException – PDOException represents errors raised by PDO.

<?php

    $dbuser = "root";
    $dbpass = "pass"; //If your Db have a Password

    try{

            $dbPDO = new PDO('mysql:host=localhost;dbname=hotelDB', $dbuser, $dbpass);
            $dbPDO->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
            $pdo->exec('SET NAMES "utf8"');
            echo "Database connected successfully";

    } catch(PDOException $e){

            print "Error!: " . $e->getMessage() . "<br />";
            die();

    }

    //On successful connection.   
    $SuccessResult = "Secure Database Connection established.";

?>

Some Popular Databases supported by PDO :

  • MySQL
  • PostgreSQL
  • Oracle
  • Firebird
  • MS SQL Server
  • Sybase Informix
  • IBM

In this blog, we learned How to Connect to MySQL Database Using PHP, you can connect your database using many ways.

Also Read:

How to copy input value to another form through jquery, Easy Form Validation With jQuery