Follow The New Tutorial updates on WhatsApp, Telegram or YouTube.

PHP MySQLi Connect

If you want to access data from MySQLi database, first you need to make connection with server.

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

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

Open a Connection to MySQL

Example – MySQLi 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";
?>

mysqli_connect()

PHP mysqli_connect() function is used to connect with MySQL database. It returns resource if connection is established or null.

Syntax
resource mysqli_connect (server, username, password);

Example – MySQLi Object-Oriented

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

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

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

Example – PDO

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

PDO require a valid database to connect to. If no database is specified, an exception is thrown.

Close the Connection

The connection will be closed automatically when the script ends. To close the connection before, use the following.

MySQLi Procedural

mysqli_close($conn);

PHP mysqli_close()

PHP mysqli_close() function is used to disconnect with MySQL database. It returns true if connection is closed.

Syntax
bool mysqli_close(resource $resource_link)  

MySQLi Object-Oriented

$conn->close();

PDO

$conn = null;