MYSQL Connect

Last Updated: March 7, 2022

You can use the following methods to connect to MYSQL with PHP

  • MYSQLi extention
  • PDO (PHP Data Object)

What is the best method for connection?

MYSQLi works only with MYSQL. But PDO supports12 different database systems.

You can use whatever method you like.

If you have the plan to change the database for your application at a later stage then PDO is the best because you have to change only the connection string to the database.

Changing a database is very hard if you use MYSQLi because you have to rewrite all database-related code.

Installation

MYSQLi installation

PDO Installation

Open a connection to MYSQL Database

MYSQLi connection (Object Oriented)

<?php
$host = "localhost";
$username = "root";
$password = "";

// Create connection
$conn = new mysqli($host, $username, $password);

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

To close the connection $conn->close();

MySQLi connection procedural

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

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

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

To close the connection mysqli_close($conn);

PDO Example

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

To close the connection $conn = null;

Test