PHP中SQL操作affected_rows()
作用:afftected_rows()函数的作用是获取上一个执行MySQL操作所影响的行数,然后判断是否执行成功。
适用于INSERT,UPDATE,DELETE等操作。
$conn = mysqli_connect("localhost", "username", "password", "database"); if(mysqli_connect_errno()) { echo "数据库连接失败:" . mysqli_connect_error(); exit(); } $query = "INSERT INTO users(name, age, email) VALUES('Alice', '25', 'alice@example.com')"; if(mysqli_query($conn, $query)) { $affected_rows = mysqli_affected_rows($conn); echo "插入了 " . $affected_rows . " 行数据。"; } else { echo "插入数据失败:" . mysqli_error($conn); } mysqli_close($conn);
// 执行一条UPDATE语句 $query = "UPDATE users SET age='30' WHERE name='Alice'"; mysqli_query($conn, $query); $affected_rows = mysqli_affected_rows($conn); echo "更新了 " . $affected_rows . " 行数据。"; // 执行一条DELETE语句 $query = "DELETE FROM users WHERE age='30'"; mysqli_query($conn, $query); $affected_rows = mysqli_affected_rows($conn); echo "删除了 " . $affected_rows . " 行数据。";