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, providing a step‑by‑step example that creates a connection, runs a SELECT 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 PHP provides functions to connect and operate MySQL databases, among which the mysqli_query function is commonly used to execute queries.

The mysqli_query function can run SELECT, INSERT, UPDATE, DELETE and other SQL statements; it takes a database connection object and a query string as parameters. Below is a complete example that demonstrates 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 creates a connection, checks it, runs the SELECT statement, stores the result in $result, iterates over each row to output ID, name, and age, then frees the result set and closes the connection.

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

When mysqli_query runs a query, it returns a result set object; functions like mysqli_fetch_assoc, mysqli_fetch_row, and mysqli_fetch_array can be used to retrieve rows in different formats.

In summary, using PHP’s mysqli_query to perform MySQL operations is convenient and efficient for SELECT, INSERT, UPDATE, and DELETE tasks.

Java学习资料领取

C语言学习资料领取

前端学习资料领取

C++学习资料领取

php学习资料领取

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

databasemysqlPHPmysqli_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

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.