PHP mysqli_num_rows: Count Rows Easily
In PHP, the mysqli_num_rows function is used to retrieve the number of rows in a result set. The usage is as follows:
- First, you need to create a mysqli object and connect to the database. For example:
$conn = new mysqli("localhost", "username", "password", "database");
- Next, use the mysqli_query function to execute the SQL query and store the result in a variable. For example:
$query = "SELECT * FROM table";
$result = mysqli_query($conn, $query);
- Finally, use the mysqli_num_rows function to retrieve the number of rows in the result set. For example:
$rowCount = mysqli_num_rows($result);
echo "总共有 " . $rowCount . " 行数据";
The complete sample code is shown below:
$conn = new mysqli("localhost", "username", "password", "database");
$query = "SELECT * FROM table";
$result = mysqli_query($conn, $query);
$rowCount = mysqli_num_rows($result);
echo "总共有 " . $rowCount . " 行数据";
Before using the mysqli_num_rows function, it is necessary to first execute the mysqli_query function to perform a query and retrieve the result set. Additionally, before using the mysqli_num_rows function, make sure that the database connection has been established.