Backend Development 4 min read

Using PHP mysqli_query to Execute MySQL Queries

This article explains how to use PHP's mysqli_query function to perform MySQL operations such as SELECT, INSERT, UPDATE, and DELETE, including a full example that creates a connection, runs a query, processes results, and closes the connection.

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 it is common to perform various query operations. PHP, a popular server‑side language, provides many functions for connecting to and working with MySQL databases; the mysqli_query function is one of the most frequently used for executing queries.

The mysqli_query function can run SELECT, INSERT, UPDATE, DELETE and other SQL statements. It takes two arguments: the database connection object and the query string. Below is a sample code that uses mysqli_query to perform a SELECT query:

<?php
// 创建数据库连接
$connection = mysqli_connect('localhost', 'username', 'password', 'database');
// 检查连接是否成功
if (!$connection) {
die('数据库连接失败: ' . mysqli_connect_error());
}
// 执行SELECT查询
$query = "SELECT id, name, age FROM users";
$result = mysqli_query($connection, $query);
// 检查查询是否成功
if (!$result) {
die('查询失败: ' . mysqli_error($connection));
}
// 处理查询结果
while ($row = mysqli_fetch_assoc($result)) {
echo 'ID: ' . $row['id'] . ', 姓名: ' . $row['name'] . ', 年龄: ' . $row['age'] . '<br>';
}
// 释放结果集
mysqli_free_result($result);
// 关闭数据库连接
mysqli_close($connection);
?>

The example first creates a database connection and checks its success, then executes a SELECT statement, stores the result in $result , iterates over the rows with mysqli_fetch_assoc to print each ID, name and age, frees the result set, and finally closes the connection.

Beyond SELECT, mysqli_query can also execute INSERT, UPDATE, DELETE and other statements by passing the appropriate SQL as the second argument.

It is important to remember that mysqli_query returns a result set object for queries that produce results; you can retrieve rows using mysqli_fetch_assoc , mysqli_fetch_row , mysqli_fetch_array , etc.

In summary, using PHP’s mysqli_query function provides a convenient and fast way to interact with a MySQL database for all basic CRUD operations.

PHP速学教程(入门到精通)

扫描二维码免费领取学习资料

backendDatabaseMySQLPHPQuerymysqli
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.