mysqli_stmt_num_rows()函數(shù)返回語句結(jié)果集中的行數(shù)。
mysqli_stmt_num_rows()函數(shù)接受一個(gè)語句對(duì)象作為參數(shù),并返回給定語句結(jié)果集中的行數(shù)。
mysqli_stmt_num_rows($stmt)
序號(hào) | 參數(shù)及說明 |
---|---|
1 | stmt(必需) 這是表示執(zhí)行SQL查詢的語句的對(duì)象。 |
PHP mysqli_stmt_num_rows()函數(shù)返回一個(gè)整數(shù)值,該值指示該語句返回的結(jié)果集中的行數(shù)。
此函數(shù)最初是在PHP版本5中引入的,并且可以在所有更高版本中使用。
以下示例演示了mysqli_stmt_num_rows()函數(shù)的用法(面向過程風(fēng)格)-
<?php $con = mysqli_connect("localhost", "root", "password", "mydb"); mysqli_query($con, "CREATE TABLE Test(Name VARCHAR(255), AGE INT)"); print("創(chuàng)建表.....\n"); mysqli_query($con, "insert into Test values('Raju', 25),('Rahman', 30),('Sarmista', 27)"); print("插入記錄.....\n"); //讀取記錄 $stmt = mysqli_prepare($con, "SELECT * FROM Test"); //執(zhí)行語句 mysqli_stmt_execute($stmt); mysqli_stmt_store_result($stmt); //行數(shù) $count = mysqli_stmt_num_rows($stmt); print("表中的行數(shù): ".$count."\n"); //結(jié)束語句 mysqli_stmt_close($stmt); //關(guān)閉連接 mysqli_close($con); ?>
輸出結(jié)果
創(chuàng)建表..... 插入記錄..... 表中的行數(shù): 3
在面向?qū)ο箫L(fēng)格中,此函數(shù)的語法為$con->num_rows;。以下是面向?qū)ο箫L(fēng)格中此函數(shù)的示例;
<?php //建立連接 $con = new mysqli("localhost", "root", "password", "mydb"); $con -> query("CREATE TABLE Test(Name VARCHAR(255), AGE INT)"); print("創(chuàng)建表.....\n"); $con -> query("insert into Test values('Raju', 25),('Rahman', 30),('Sarmista', 27)"); print("插入記錄.....\n"); $stmt = $con -> prepare( "SELECT * FROM Test"); //執(zhí)行語句 $stmt->execute(); $stmt->store_result(); //行數(shù) $count = $stmt ->num_rows; print("表中的行數(shù)".$count); //結(jié)束語句 $stmt->close(); //關(guān)閉連接 $con->close(); ?>
輸出結(jié)果
創(chuàng)建表..... 插入記錄..... 表中的行數(shù): 3
假設(shè)我們用下面的數(shù)據(jù)創(chuàng)建了一個(gè)名為cricketers的表;
mysql> select * from cricketers; +----+------------+------------+---------------+----------------+ | ID | First_Name | Last_Name | Date_Of_Birth | Place_Of_Birth | +----+------------+------------+---------------+----------------+ | 1 | Shikhar | Dhawan | 1981-12-05 | Delhi | | 2 | Jonathan | Trott | 1981-04-22 | CapeTown | | 3 | Kumara | Sangakkara | 1977-10-27 | Matale | | 4 | Virat | Kohli | 1988-11-05 | Delhi | | 5 | Rohit | Sharma | 1987-04-30 | Nagpur | | 6 | Ravindra | Jadeja | 1988-12-06 | Nagpur | +----+------------+------------+---------------+----------------+ 6 rows in set (0.07 sec)
如果您嘗試直接調(diào)用這個(gè)函數(shù),因?yàn)榻Y(jié)果還沒有存儲(chǔ),則返回0 :
<?php $con = mysqli_connect("localhost", "root", "password", "mydb"); //Reading records $stmt = mysqli_prepare($con, "SELECT * FROM cricketers"); //執(zhí)行語句 mysqli_stmt_execute($stmt); print("表中的行數(shù): ".mysqli_stmt_num_rows($stmt)); //結(jié)束語句 mysqli_stmt_close($stmt); //關(guān)閉連接 mysqli_close($con); ?>
輸出結(jié)果
表中的行數(shù): 0