Use the PHP function 'mysqli_num_rows' to get the number of rows in the result set

王林
Release: 2023-07-25 06:28:01
Original
998 people have browsed it

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();
?>
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template