Using PHP mysqli_query to Execute MySQL Queries
This article explains how to use PHP's mysqli_query function to perform MySQL SELECT, INSERT, UPDATE, and DELETE operations, provides a complete example script with connection handling, query execution, result processing, and highlights related functions for fetching data.
MySQL is a widely used relational database management system, and when developing web applications it is common to execute various queries. PHP, a popular server‑side language, offers many functions for connecting to and operating MySQL databases, among which the mysqli_query function is frequently used to run queries.
The mysqli_query function can execute all types of MySQL statements, including SELECT, INSERT, UPDATE, and DELETE. It takes two arguments: the database connection object and the SQL query string. The following example demonstrates using 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 script first creates a database connection and verifies its success. It then runs a SELECT statement with mysqli_query, storing the result in the $result variable. By looping over $result with mysqli_fetch_assoc, each row’s ID, name, and age are printed. Finally, the result set is freed and the connection closed.
Beyond SELECT, mysqli_query can execute other statements such as INSERT, UPDATE, and DELETE by passing the appropriate SQL as the second argument.
Note that mysqli_query returns a result‑set object for queries that produce results. 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 way to interact with MySQL databases for a variety of operations, making it easy to perform SELECT, INSERT, UPDATE, and DELETE tasks.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
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.
