Current Location: Home> Latest Articles> PHP Database Tutorial: How to Use mysqli_connect to Connect to MySQL Database

PHP Database Tutorial: How to Use mysqli_connect to Connect to MySQL Database

gitbox 2025-06-16

Introduction:

In web development, database operations are an essential part of managing large amounts of data, providing persistence and security. PHP is a widely used scripting language for web development that offers many functions and interfaces for database operations. This article will introduce how to use PHP's mysqli_connect function to connect to a MySQL database, along with some code examples.

1. Prerequisites:

Before using the mysqli_connect function, ensure the following:

  1. You have PHP correctly installed and configured.
  2. You have MySQL installed and know the MySQL database's hostname, username, password, and other relevant information.

2. Connecting to MySQL Database:

In PHP, we can use the mysqli_connect function to connect to a MySQL database. The basic syntax of the function is as follows:

mysqli_connect(host, username, password);
  

host: Specifies the MySQL server's hostname, which can be an IP address or a domain name.

username: The username used to log into the MySQL database.

password: The password used to log into the MySQL database.

Here is a practical example, where the MySQL database's hostname is "localhost", the username is "root", and the password is empty:

$host = "localhost";
$username = "root";
$password = "";

$conn = mysqli_connect($host, $username, $password);

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

echo "Connection successful";
  

In the above example, we first define the MySQL server's hostname, username, and password. Then, we use the mysqli_connect function to establish a connection and assign the returned connection object to the $conn variable. Finally, we use the mysqli_connect_error function to check if the connection was successful. If there is an error, it will print the error message and the connection will fail. If the connection is successful, "Connection successful" will be displayed.

3. Closing the Database Connection:

After using the database, it is important to close the connection to release resources. You can use the mysqli_close function to close the database connection. Here is an example:

mysqli_close($conn);
  

4. Conclusion:

This article introduced how to use PHP's mysqli_connect function to connect to a MySQL database and provided corresponding code examples. Connecting to a MySQL database is the foundational step in database operations, and mastering this basic skill will lay a solid foundation for subsequent database tasks. We hope this article helps you get started with PHP database operations.

That's the introduction to PHP database operations. We hope it is helpful to you.