PHP Database Connection Manual: Connect to the database: Use the mysqli_connect() function to specify the host name, user name, password and database name. Check for connection errors: Use the mysqli_connect_error() function to check the connection for errors. Close the connection: Use the mysqli_close() function to close the database connection. Execute a query: Use the mysqli_query() function to execute a SQL query. Get query results: Use the mysqli_fetch_assoc() function to get query results.
Introduction
Database connection is a Web application A vital component in program development. PHP provides flexible and powerful tools for interacting with databases, but understanding the ins and outs of your connections is critical to ensuring your application runs smoothly and is secure. This document guides you in exploring all aspects of PHP database connectivity, from basic concepts to advanced techniques.
Connect to the database
To connect to the database, you need to use the mysqli_connect() function. This function accepts the following parameters:
mysqli_connect(hostname, username, password, database_name);
For example:
$mysqli = mysqli_connect("localhost", "my_user", "my_password", "my_database");
Check for connection errors
After connecting, be sure to check for errors. You can use the mysqli_connect_error() function:
if (mysqli_connect_errno()) { echo "Failed to connect to MySQL: " . mysqli_connect_error(); }
Close the connection
After you have finished using the database connection, be sure to close it. You can use the mysqli_close() function:
mysqli_close($mysqli);
Execute a query
To execute a SQL query, you can use the mysqli_query() function. This function accepts the following parameters:
mysqli_query(connection, query);
For example:
$result = mysqli_query($mysqli, "SELECT * FROM users");
Get query results
After executing the query, you can use the mysqli_fetch_assoc() function to get the results :
while ($row = mysqli_fetch_assoc($result)) { echo "User: " . $row['name'] . "\n"; }
Practical case
The following is a complete example showing how to connect to a MySQL database, execute a query and get the results:
The above is the detailed content of Expert Manual of PHP Database Connection: Master all aspects of database connection. For more information, please follow other related articles on the PHP Chinese website!