Skip to content
Related Articles

Related Articles

Improve Article

Connect PHP to MySQL

  • Difficulty Level : Basic
  • Last Updated : 01 Jul, 2021
Geek Week

How we can connect PHP to MySQL?

PHP 5 and later can work with a MySQL database using:

  • MySQLi extension (the ‘i’ is abbreviation for improved)
  • PDO (PHP Data Objects)

 Which one should we use MySQLi or PDO?

Both MySQLi and PDO have their recompenses:

  • PDO will work with 12 different database systems, whereas MySQLi will only work with MySQL databases.
  • So, if you have to shift your project to use alternative database, PDO makes the process easy. You only have to change the connection string and a few queries. With MySQLi, you will need to rewrite the complete code — queries included.
  • Both are object-oriented, but MySQLi also offers a procedural API.

In short, you can choose whichever you want if you want to stick to MySQL otherwise you should go with PDO.



Connection to MySQL using MySQLi

It can be done in two ways:

MySQLi Object-Oriented

        

PHP




<?php
$servername = "localhost";
$username = "username";
$password = "password";
 
// Connection
$conn = new mysqli($servername,
           $username, $password);
 
// For checking if connection is
// successful or not
if ($conn->connect_error) {
  die("Connection failed: "
      . $conn->connect_error);
}
echo "Connected successfully";
?>

MySQLi Procedural

PHP




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

Connection to MySQL using PDO

PHP




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



My Personal Notes arrow_drop_up
Recommended Articles
Page :