i

PHP Tutorial

MySQL Connect

You can connect your PHP with MySQL database using PDO or MySQLi extension.

  • PDO stands for PHP Data objects and is object oriented. It works on 12 different database systems  and if you want to later switch to another database, PDO is very useful.

  • MySQLi stands for MySQL improved. It only works with MySQL database and if you want to change database you need to write all the queries again. It offers a procedural API along with Object oriented features.

Before you access the database, you should open a connection to MySQL, and you can do it as below:

MySQLi Object Oriented

$server_name = "localhost";
$user = "username";
$pwd = "password";

// To Create connection use below statement
$conn = new mysqli($server_name, $user, $pwd);

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

MySQLi Procedural

$server_name = "localhost";
$user = "username";
$pwd = "password";

// To Create connection use below statement
$conn = mysqli_connect($server_name, $user, $pwd);

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

PDO

$server_name = "localhost";
$user = "username";
$pwd = "password";

try {
    $conn = new PDO("mysql:host=$server_name;dbname=myDB", $user, $pwd);
    // 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();
    }
?>

In PDO you need to mention a database to connect to as it can connect to various databases.

Closing the connection

When the script ends, the connection to database is automatically closed, but if you want to close it early you can use below statements.

For MySQLi Object oriented:

$conn ->close();

For MySQLi Procedural:

mysqli_close($conn);

For PDO:

$conn = null;