mysqli_fetch_all()函數(shù)從結(jié)果集中取得所有行作為關(guān)聯(lián)數(shù)組,或數(shù)字?jǐn)?shù)組,或二者兼有。
PHP result對象(mysqli_result類)表示MySQL結(jié)果,由SELECT或DESCRIBE或EXPLAIN查詢返回。
mysqli_fetch_all函數(shù)的作用是:接受一個結(jié)果對象作為參數(shù),檢索給定結(jié)果對象中的所有行。
mysqli_fetch_all($result, [$type]);
序號 | 參數(shù)及說明 |
---|---|
1 | result(必需) 這是表示結(jié)果對象的標(biāo)識符。 |
2 | type(必需) 這是一個整數(shù)值,指定返回數(shù)組的類型。type的值是以下值之一-
|
PHP mysqli_fetch_all()函數(shù)返回一個數(shù)組(關(guān)聯(lián)或數(shù)字),該數(shù)組包含結(jié)果對象的行。
此函數(shù)最初是在PHP版本5中引入的,并且可以在所有更高版本中使用。
以下示例演示了mysqli_fetch_all()函數(shù)的用法(面向過程風(fēng)格),從結(jié)果集中取得所有行作為關(guān)聯(lián)數(shù)組:
<?php $con = mysqli_connect("localhost", "root", "password", "mydb"); mysqli_query($con, "CREATE TABLE myplayers(ID INT, First_Name VARCHAR(255), Last_Name VARCHAR(255), Place_Of_Birth VARCHAR(255), Country VARCHAR(255))"); print("創(chuàng)建表.....\n"); mysqli_query($con, "INSERT INTO myplayers values(1, 'Sikhar', 'Dhawan', 'Delhi', 'India')"); mysqli_query($con, "INSERT INTO myplayers values(2, 'Jonathan', 'Trott', 'CapeTown', 'SouthAfrica')"); mysqli_query($con, "INSERT INTO myplayers values(3, 'Kumara', 'Sangakkara', 'Matale', 'Srilanka')"); print("插入記錄.....\n"); //檢索表的內(nèi)容 $res = mysqli_query($con, "SELECT * FROM myplayers"); //獲取結(jié)果的所有行 $rows = mysqli_fetch_all($res); print_r($rows); //結(jié)束語句 mysqli_free_result($res); //關(guān)閉連接 mysqli_close($con); ?>
輸出結(jié)果
創(chuàng)建表..... 插入記錄..... Array ( [0] => Array ( [0] => 1 [1] => Sikhar [2] => Dhawan [3] => Delhi [4] => India ) [1] => Array ( [0] => 2 [1] => Jonathan [2] => Trott [3] => CapeTown [4] => SouthAfrica ) [2] => Array ( [0] => 3 [1] => Kumara [2] => Sangakkara [3] => Matale [4] => Srilanka ) )
在面向?qū)ο箫L(fēng)格中,此函數(shù)的語法為$result->fetch_all();。以下是面向?qū)ο箫L(fēng)格中此函數(shù)的示例,從結(jié)果集中取得所有行作為關(guān)聯(lián)數(shù)組:
<?php //建立連接 $con = new mysqli("localhost", "root", "password", "mydb"); $con -> query("CREATE TABLE Test(Name VARCHAR(255), AGE INT)"); $con -> query("insert into Test values('Raju', 25),('Rahman', 30),('Sarmista', 27)"); print("創(chuàng)建表.....\n"); $stmt = $con -> prepare( "SELECT * FROM Test WHERE Name in(?, ?)"); $stmt -> bind_param("ss", $name1, $name2); $name1 = 'Raju'; $name2 = 'Rahman'; //執(zhí)行語句 $stmt->execute(); //檢索結(jié)果 $result = $stmt->get_result(); //讀取所有行 $rows = $result->fetch_all(); print_r($rows); //結(jié)束語句 $stmt->close(); //關(guān)閉連接 $con->close(); ?>
輸出結(jié)果
創(chuàng)建表..... Array ( [0] => Array ( [0] => Raju [1] => 25 ) [1] => Array ( [0] => Rahman [1] => 30 ) )