Here we are solving a basic problem faced by a beginner web developer in PHP i.e. Connect to MySQL database using MySQLi.

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

1) MySQLi extension (the "i" stands for improved)
2) PDO (PHP Data Objects)


MySQLi Installation

For Linux and Windows: The MySQLi extension is automatically installed in most cases, when php5 mysql package is installed. For installation details, go to: http://php.net/manual/en/mysqli.installation.php

Open a Connection to MySQL

Before we can access data in the MySQL database, we need to be able to connect to the server. The following code is MySQLi Object-Oriented code.

<?php
$sn = "example.com";
$un = "somename";
$ps = "somepassword";
$conn = new mysqli($sn, $un, $ps);
if ($conn->connect_error) 
{
    die("Connection failure" . $conn->connect_error);
} 
echo "Connection success";
?>
Now, the below code is MySQLi Procedural code.

<?php
$sn = "example.com";
$un = "somename";
$ps = "somepassword";
$conn = mysqli_connect($sn, $un, $ps);
if (!$conn) 
{
    die("Connection failure" . mysqli_connect_error());
}
echo "Connection success";
?>
Close the Connection

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

For MySQLi Object-Oriented:

$conn->close();
For MySQLi Procedural:

mysqli_close($conn);