Using PHP mysqli_query to Execute MySQL Queries
This article explains how to use PHP's mysqli_query function to connect to a MySQL database, execute SELECT queries, handle result sets, and perform other operations such as INSERT, UPDATE, and DELETE, including a complete example code snippet and best practices for error handling.
MySQL is a widely used relational database management system, and when developing web applications PHP provides several functions to connect to and operate MySQL databases. Among them, the mysqli_query function is a common way to execute query operations.
The mysqli_query function can run various types of MySQL statements, including SELECT, INSERT, UPDATE, DELETE, etc. It accepts two parameters: the database connection object and the SQL query string. Below is a complete example that demonstrates a SELECT query.
';
}
// Free result set
mysqli_free_result($result);
// Close connection
mysqli_close($connection);
?>The code first creates a database connection and verifies it, then uses mysqli_query to run a SELECT statement and stores the result in the $result variable. It iterates over $result with mysqli_fetch_assoc to print each row's ID, name, and age, and finally frees the result set and closes the connection.
Beyond SELECT, mysqli_query can execute other statements such as INSERT to add data, UPDATE to modify data, and DELETE to remove data; you simply pass the appropriate SQL as the second argument.
When mysqli_query runs a SELECT statement, it returns a result set object. You can retrieve rows from this object using functions like mysqli_fetch_assoc , mysqli_fetch_row , or mysqli_fetch_array , depending on the desired format.
In summary, using PHP's mysqli_query function provides a convenient and efficient way to perform MySQL operations such as SELECT, INSERT, UPDATE, and DELETE within web applications.
php中文网 Courses
php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.