Using PHP mysqli_query to Execute MySQL Queries
This article explains how the PHP mysqli_query function can be used to run SELECT, INSERT, UPDATE, and DELETE statements against a MySQL database, provides a complete example with connection handling, error checking, result processing, and highlights related fetching functions.
MySQL is a widely used relational database management system, and when developing web applications PHP offers several functions to connect to and operate MySQL databases. The mysqli_query function is one of the most common ways to execute queries.
mysqli_query can run various types of SQL statements, including SELECT , INSERT , UPDATE , and DELETE . It takes two parameters: the database connection object and the SQL query string. The following example demonstrates a SELECT query.
';
}
// 释放结果集
mysqli_free_result($result);
// 关闭数据库连接
mysqli_close($connection);
?>The code first creates a database connection and checks for success. It then uses mysqli_query to execute a SELECT statement, stores the result in $result , and iterates over the rows with mysqli_fetch_assoc to print each record's ID, name, and age. Finally, it frees the result set and closes the connection.
Beyond SELECT , the same function can execute other statements such as INSERT , UPDATE , and DELETE by passing the appropriate SQL as the second argument.
When mysqli_query runs a SELECT , it returns a result set object. You can retrieve rows using functions like mysqli_fetch_assoc , mysqli_fetch_row , or mysqli_fetch_array , depending on the desired format.
In summary, the PHP mysqli_query function provides a convenient and efficient way to interact with MySQL databases for a variety of CRUD operations.
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.