Home >Backend Development >PHP Tutorial >How to connect to a MySQL database using PHP?
To connect to a MySQL database using PHP, follow these steps: Include the MySQLi library. Connect to the database using the mysqli_connect() function, providing the hostname, username, password, and database name. Checks whether the connection was successful and handles any errors.
How to use PHP to connect to a MySQL database
Connecting to a MySQL database is an essential step in PHP development. This article will guide you step-by-step through connecting to a MySQL database using the MySQLi extension for PHP.
Step 1: Include the necessary libraries
At the beginning of the PHP script, include the MySQLi extension library:
<?php include 'mysqli.php'; ?>
Step 2 : Connect to the database
Use the mysqli_connect()
function to connect to the MySQL database. This function requires the following four parameters:
For example:
$conn = mysqli_connect('localhost', 'username', 'password', 'database_name');
Step 3: Detect connection errors
Always check whether the connection is successful. If the connection fails, mysqli_connect()
will return false
:
if (!$conn) { die('无法连接到数据库:' . mysqli_connect_error()); }
Practical case: Get all users
to be obtained from To get all users in the database, you can use the following query:
$query = "SELECT * FROM users"; $result = mysqli_query($conn, $query); if ($result) { while ($row = mysqli_fetch_assoc($result)) { // 处理每行数据 echo $row['name'] . ' ' . $row['email'] . '<br>'; } } else { die('查询失败:' . mysqli_error($conn)); }
Conclusion
The above are the steps to use PHP to connect to the MySQL database and execute the query. By following these steps, you can easily connect your PHP application to a MySQL database.
The above is the detailed content of How to connect to a MySQL database using PHP?. For more information, please follow other related articles on the PHP Chinese website!