Introduction and usage of mysql_affected_rows() in MySQL

Abstract: This article will introduce in detail the concept and usage of the mysql_affected_rows() function in the MySQL database. Through examples and output results, it shows how to use this function to obtain the number of rows affected by the execution of SQL statements, helping readers better understand and apply this function.

1. What is mysql_affected_rows()

mysql_affected_rows() is a PHP function provided by the MySQL database, which is used to obtain the number of rows affected by the execution of the latest SQL statement. It is usually used after operations such as INSERT, UPDATE, and DELETE to obtain the number of affected rows in the program.

2. Use mysql_affected_rows()

Using mysql_affected_rows() is very simple, just call the function after executing the SQL statement. Here is an example:

<?php
// 连接到数据库
$conn = mysqli_connect("localhost", "username", "password", "database");

// 执行SQL语句
mysqli_query($conn, "UPDATE users SET age = 30 WHERE id = 1");

// 获取受影响的行数
$affectedRows = mysqli_affected_rows($conn);

// 输出结果
echo "受影响的行数:" . $affectedRows;

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

In the above example, we first connected to the database and then executed an UPDATE statement to update the age of the user with ID 1 to 30. Next, use the mysql_affected_rows() function to get the number of affected rows and output the result.

3. Output the result

The following is the output of the sample code after execution:

受影响的行数:1

In this example, since we only updated one row of data, the number of affected rows is 1.

4. Summary

Through the mysql_affected_rows() function, we can easily obtain the number of rows affected by the latest SQL statement execution. This is useful for scenarios where statistics or verification of the results of operations is required. This article introduces the concept and usage of the mysql_affected_rows() function, and shows readers the specific operation steps and output results through examples.

Hope this article helps you understand and apply the mysql_affected_rows() function!

Guess you like

Origin blog.csdn.net/weixin_65846839/article/details/131934152
Recommended