PHP : MySQL Connect

Before PHP can read or save data, it must make a connection with the MySQL server. In this chapter you will learn how to connect using the MySQLi extension (MySQL Improved). It is enabled by default in XAMPP and in almost all hosting.


Syntax of mysqli_connect()

mysqli_connect(hostname, username, password, database, port, socket);
ParameterDescription
hostnameRequired. The MySQL server name. Use localhost for your own computer. A port can be added like “localhost:3307”
usernameRequired. The MySQL user. On a local XAMPP server it is usually root
passwordRequired. The password of that user. On local XAMPP it is empty ("")
databaseOptional. The database to use after connecting
port, socketOptional. Only needed if your server uses a different port or socket

On success it returns a connection object. If the connection fails, older PHP versions return false, and from PHP 8.1 an exception (mysqli_sql_exception) is thrown.


Example: connect to the MySQL server

<?php
$database_server = 'localhost';
$database_username = 'root';
$database_password = '';

$conn = mysqli_connect($database_server, $database_username, $database_password);

if (!$conn) {
    die("Connection failed: " . mysqli_connect_error());
}

echo "Connected successfully";

mysqli_close($conn);
?>

Output:

Tutorials Class - Output Window

Connected successfully

mysqli_connect_error() shows the reason when the connection fails, for example a wrong password. mysqli_close() closes the connection at the end. PHP also closes it itself when the script finishes.


Handle connection errors in PHP 8.1 and above

Now a failed connection throws an exception, so the if (!$conn) check is never reached. Use try and catch to show a friendly message.

<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);

try {
    $conn = mysqli_connect("localhost", "root", "wrong_password");
} catch (mysqli_sql_exception $e) {
    echo "Connection failed: " . $e->getMessage();
}
?>

Output:

The exact text can be different on your server

Connection failed: Access denied for user ‘root’@’localhost’ (using password: YES)


A reusable connection file

You need the connection in every page that uses the database. So write the code once in a file named db-connection.php and include it with require_once (see PHP File Inclusion). This file also selects the student database that we create in the next chapter, and all next chapters use it.

<?php
// db-connection.php
$database_server = 'localhost';
$database_username = 'root';
$database_password = '';
$database_name = 'student';

// Create connection using mysqli_connect()
$conn = mysqli_connect($database_server, $database_username, $database_password, $database_name);

// If $conn is false, connection is failed
if (!$conn) {
    die("Failed to connect to MySQL: " . mysqli_connect_error());
}
?>
Note: root with an empty password is only for learning on your computer. On a live website create a separate MySQL user with a strong password, and keep this file outside the public folder.

Object oriented style

The same connection can be written in the object oriented style. Read the difference in MySQLi Procedural vs Object Oriented.

<?php
$conn = new mysqli("localhost", "root", "");

echo "Connected successfully";
?>

Next chapter: PHP : MySQL Create Database.


Congratulations! Chapter Finished. Learn more about the similar topics:
Exercises & Assignments
No Content Found.
Interview Questions & Answers
No Content Found.