Use the PHP function "mysqli_num_rows" to get the number of rows in the result set
When using PHP for database operations, sometimes we need to get the number of rows in the query result set. PHP provides a very convenient function "mysqli_num_rows" to get the number of rows in the result set.
The following is a sample code that demonstrates how to use the "mysqli_num_rows" function to get the number of rows in the result set:
<?php // 假设已经连接到数据库 $mysqli = new mysqli('localhost', 'username', 'password', 'database_name'); // 检查数据库连接是否成功 if ($mysqli->connect_errno) { echo "连接数据库失败:" . $mysqli->connect_error; exit(); } // 执行查询语句 $query = "SELECT * FROM users"; $result = $mysqli->query($query); // 检查查询语句是否执行成功 if (!$result) { echo "查询失败:" . $mysqli->error; exit(); } // 使用 mysqli_num_rows 函数获取结果集中的行数 $num_rows = mysqli_num_rows($result); // 打印结果 echo "结果集中的行数为:" . $num_rows; // 关闭数据库连接 $mysqli->close(); ?>
In the above sample code, we first connect to the database and then execute A query statement that saves the query result set to the variable $result. We then use the "mysqli_num_rows" function to get the number of rows in the result set and save it to the variable $num_rows. Finally, we output the line number to the page through the echo statement.
It should be noted that the "mysqli_num_rows" function can only be used after the query statement is successfully executed. If the query statement fails, there is no data in the result set, so the "mysqli_num_rows" function will return 0.
Summary:
Use the PHP function "mysqli_num_rows" to easily get the number of rows in the result set. This is very practical when performing database operations. It can help us determine whether there is data returned and count the number of rows in query results.
The above is the detailed content of Use the PHP function 'mysqli_num_rows' to get the number of rows in the result set. For more information, please follow other related articles on the PHP Chinese website!