Function name: mysqli_stmt::$num_rows()
Applicable version: PHP 5, PHP 7
Usage: the mysqli_stmt::$num_rows() function is used to get the number of rows in the result set returned by the preprocessing statement.
Syntax: int mysqli_stmt::$num_rows ( void )
Parameters: None
Return value: Returns the number of rows in the result set, and if the result set is empty, return 0.
Example:
// 创建数据库连接$mysqli = new mysqli("localhost", "username", "password", "dbname"); // 检查连接是否成功if ($mysqli->connect_errno) { echo "连接数据库失败:" . $mysqli->connect_error; exit(); } // 准备预处理语句$query = "SELECT * FROM users WHERE age > ?"; $stmt = $mysqli->prepare($query); // 绑定参数$minAge = 18; $stmt->bind_param("i", $minAge); // 执行预处理语句$stmt->execute(); // 存储结果集$stmt->store_result(); // 获取结果集中的行数$numRows = $stmt->num_rows; // 输出行数echo "结果集中的行数:" . $numRows; // 关闭预处理语句和数据库连接$stmt->close(); $mysqli->close();
In the above example, we first create a database connection and then prepare a preprocessing statement containing a parameter placeholder. We bind a parameter value, then execute the preprocessing statement and store the result set. Finally, by calling the mysqli_stmt::$num_rows() function, we take the number of rows in the result set and output it.
Note that before using the mysqli_stmt::$num_rows() function, the mysqli_stmt::$store_result() function must be executed in order to store the result set in memory, otherwise the function will return 0.