PHP mysqli_num_rows Tutorial
The mysqli_num_rows function is used to retrieve the number of rows in a result set. The usage is as follows:
1. Establish a connection to the database:
$conn = mysqli_connect("localhost", "username", "password", "database_name");
if (!$conn) {
die("连接失败: " . mysqli_connect_error());
}
2. Execute an SQL query and retrieve the result set.
$sql = "SELECT * FROM table_name";
$result = mysqli_query($conn, $sql);
3. Retrieve the number of rows in the result set using the mysqli_num_rows function.
$row_count = mysqli_num_rows($result);
echo "行数:" . $row_count;
The complete sample code is shown below:
$conn = mysqli_connect("localhost", "username", "password", "database_name");
if (!$conn) {
die("连接失败: " . mysqli_connect_error());
}
$sql = "SELECT * FROM table_name";
$result = mysqli_query($conn, $sql);
$row_count = mysqli_num_rows($result);
echo "行数:" . $row_count;
mysqli_close($conn);
Note: Before using the mysqli_num_rows function, ensure that the SQL query has been executed and the result set has been obtained.