PHP MySql Connectivity 


Two Ways of Writing a PHP Script to Connect to MySQL

There are two methods to connect to an SQL database using PHP: MySQLi, and PDO.

One of the most important features they both support is prepared statements, which accelerates the time needed for MySQL to execute the same query multiple times. It can also be used to prevent SQL injection attacks when making changes to the database.

MySQLi stands for MySQL Improved. It is a MySQL-exclusive extension that adds new features to a MySQL database’s interface. MySQLi is both procedural and object-oriented, with the former being the attribute inherited from the older version of MySQL.

PDO stands for PHP Data Object. Unlike MySQLi, PDO is object-oriented only and supports a number of different database types that use PHP, such as MySQL, MSSQL, Informix, and PostgreSQL.

Connecting a PHP File to MySQL using MySQLi

 <?php
  $servername = "localhost";
  $database = "databasename";
  $username = "username";
  $password = "password";
  // Create connection
 $conn=mysqli_connect($servername,$username,$password, $database);
// Check connection
  if(!$conn)
   {
   die("Connection failed: " . mysqli_connect_error());
   }
   echo "Connected successfully";
   mysqli_close($conn);
   ?>

mysqli_connect():- This is an internal PHP function to establish a new connection to a MySQL server.

If the connection is not successful, the die() function is executed here, which basically kills our script and gives us a message that we have set.

mysqli_close, which will simply close the connection to a database manually. If not specified, the connection will close by itself once the script ends.


Connecting a PHP File to MySQL using PDO

The methods to connect a PHP script to MySQL using PDO is similar to the previous one, but with a slight variation:

  <?php
    $host = 'localhost';
    $dbname = 'databasename';
    $username = 'username';
    $password = 'password';
  try {
    $conn = new PDO("mysql:host=$host;dbname=$dbname",     $username, $password);

    echo "Connected to $dbname at $host successfully.";
    } 
   catch (PDOException $pe)
    {
    die("Could not connect to the database $dbname :" .   $pe->getMessage());
     }

  ?>