函式名:mysqli_result::$num_rows()
適用版本:PHP 5, PHP 7
用法:mysqli_result::$num_rows() 函式用於獲取結果集中的行數。
語法:int mysqli_result::num_rows ( void )
引數:此函式不接受任何引數。
返回值:返回結果集中的行數。
示例:
// 建立資料庫連線
$servername = "localhost";
$username = "root";
$password = "password";
$dbname = "myDB";
$conn = new mysqli($servername, $username, $password, $dbname);
// 檢查連線是否成功
if ($conn->connect_error) {
die("連線失敗: " . $conn->connect_error);
}
// 執行查詢
$sql = "SELECT * FROM customers";
$result = $conn->query($sql);
// 檢查是否有結果
if ($result->num_rows > 0) {
// 輸出每一行資料
while($row = $result->fetch_assoc()) {
echo "ID: " . $row["id"]. " - Name: " . $row["name"]. " - Email: " . $row["email"]. "<br>";
}
} else {
echo "0 結果";
}
// 關閉連線
$conn->close();
在上面的示例中,我們首先建立了一個資料庫連線,然後執行了一個查詢語句。使用 $result->num_rows 可以獲取結果集中的行數。如果行數大於0,則透過 $result->fetch_assoc() 迴圈遍歷每一行資料並輸出。如果行數為0,則輸出 "0 結果"。最後,我們關閉了資料庫連線。
請確保在使用 $result->num_rows 之前,你已經執行了查詢並獲得了結果集。
熱門工具排行榜