Backend Development 5 min read

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.

php中文网 Courses
php中文网 Courses
php中文网 Courses
Using PHP mysqli_query to Execute MySQL Queries

MySQL is a widely used relational database management system, and when developing web applications, various query operations are often needed. PHP, as a common server‑side programming language, provides many functions to connect to and operate MySQL databases. Among them, the mysqli_query function is a commonly used function for executing query operations.

The mysqli_query function can execute various types of MySQL statements, including SELECT, INSERT, UPDATE, DELETE, etc. It takes two parameters: the first is the database connection object, and the second is the SQL query string. Below is an example code that uses mysqli_query to perform a SELECT query.

';
}

// 释放结果集
mysqli_free_result($result);

// 关闭数据库连接
mysqli_close($connection);
?>

The code first creates a database connection object and checks whether the connection succeeded. Then it uses mysqli_query to execute a SELECT query, storing the result in the $result variable. Next, it loops through $result to print each row's ID, name, and age. Finally, it frees the result set and closes the connection.

In addition to SELECT, mysqli_query can execute other query types. For example, it can run INSERT statements to add data, UPDATE statements to modify data, DELETE statements to remove data, etc., by passing the appropriate SQL statement as the second argument.

Note that mysqli_query returns a result set object for SELECT queries. By iterating over this result set, you can retrieve each row. Functions such as mysqli_fetch_assoc , mysqli_fetch_row , and mysqli_fetch_array can be used to fetch results in different formats.

In summary, using PHP's mysqli_query function to perform MySQL queries is convenient and fast. Whether executing SELECT, INSERT, UPDATE, or DELETE, you simply pass the corresponding SQL statement and can easily manipulate the database.

php8, I'm here

Scan the QR code to receive free learning materials

BackendSQLDatabaseMySQLPHPmysqli_query
php中文网 Courses
Written by

php中文网 Courses

php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.