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 complete example that creates a connection, runs a query, processes results, and closes the connection.
MySQL is a widely used relational database management system, and PHP provides functions to connect and operate it; the mysqli_query function is commonly used to execute SQL statements such as SELECT, INSERT, UPDATE, and DELETE.
<?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 demonstrates creating a MySQL connection in PHP, running a SELECT query with mysqli_query, checking for errors, iterating over the result set using mysqli_fetch_assoc, and finally freeing the result and closing the connection.
Beyond SELECT, the same function can execute INSERT, UPDATE, DELETE, and other statements by passing the appropriate SQL string as the second argument.
The function returns a result set object for queries that produce data; developers can retrieve rows with mysqli_fetch_assoc, mysqli_fetch_row, or mysqli_fetch_array as needed.
In summary, using PHP’s mysqli_query offers a convenient way to perform various MySQL operations directly from server‑side code.
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.
