PHP & MySQL - Database Connect/Disconnect Tutorial

In this tutorial we learn how PHP allows us to easily connect to, and manipulate relational SQL databases like MySQL and MariaDB with its built-in mysqli() functions.

Here's a table of contents of what you'll learn in this lesson:
(click on a link to skip to its section)

Let's jump right in.

For this tutorial, please start the MySQL module in your XAMPP control panel.

How to connect to a database server

Before we can do anything in a database we need to connect to the server its running on. To do this, we use the msqli_connect() function.

Syntax:
 $result = mysqli_connect(serverName, userName, password);
Example: connect to the database server
<?php

$serverName = "localhost";
$userName = "root";
$password = "";

// create connection
$conn = mysqli_connect($serverName, $userName, $password);

// check connection
if (!$conn) {
    die("Connection failed: " . mysqli_connect_error());
} else {
	echo "Connected to server"
}

?>

In the example above, we connect to the server on the localhost (the computer its installed on) with a username of ‘root’ and an empty password.

The default XAMPP installation sets the username to ‘root’ and the password to empty. When working on a live server, your web host will give you the username and password.

An optional step is to check if the connection succeeded, and if not, raise an error with the mysqli_connect_error() function.

We should also store the connection result into a variable for later use, such as closing the connection.

How to disconnect from a database server

When the script ends, the connection will be closed automatically. However, we can manually close the connection whenever we want with the mysqli_close() function.

Syntax:
 mysqli_close(connection)
Example: disconnect from database server
<?php

$serverName = "localhost";
$userName = "root";
$password = "";

// create connection
$conn = mysqli_connect($serverName, $userName, $password);

// check connection
if (!$conn) {
    die("Connection failed: " . mysqli_connect_error());
} else {
	echo "Connected to server";
}

// close connection
mysqli_close($conn);

?>

While it’s not required to close the connection at the end of the script, it’s good practice to do so.

Summary: Points to remember

  • Before any database operations can occur, a connection to the server must be established.
  • It's good practice to manually close the connection at the end of the script.