我在做下一個查詢到數據庫爲什麼選擇*只返回第一個字段?
$result = $con->query ('select * from table');
$datos = $result->fetch_assoc();
echo "Cantidad de datos: ".count($datos).",";
print_r($datos);
應該顯示所有條目的數組,但只顯示第一個條目。爲什麼?
PS:我看到其他帖子,但我沒有限制或加入。
我在做下一個查詢到數據庫爲什麼選擇*只返回第一個字段?
$result = $con->query ('select * from table');
$datos = $result->fetch_assoc();
echo "Cantidad de datos: ".count($datos).",";
print_r($datos);
應該顯示所有條目的數組,但只顯示第一個條目。爲什麼?
PS:我看到其他帖子,但我沒有限制或加入。
FETCH_ASSOC獲取一個結果行作爲關聯數組
所以,你可以去通過所有可能的話,其獲取另一行一段時間週期的行。
$count = 0;
while($row = $result->fetch_assoc()){
// You can access data like this -->> $row['data'];
$count++;
}
echo $count;
,並在完成後,你應該釋放你的記憶,結果
$result->free();
相關,但如果你想獲得只計算,你可以使用從返回的行數mysql_num_rows結果集。
$count = mysql_num_rows($result);
echo $count;
fetch_assoc
只返回一個當你正在做$datos = $result->fetch_assoc();
中都可以PDO
和mysqli
獲取整個陣列排,下面是一個使用mysqli->fetch_all函數獲取所有行的例子,希望這有助於!
//Database Connection
$sqlConn = new mysqli($hostname, $username, $password, $database);
//Build SQL String
$sqlString = "SELECT * FROM my_table";
//Execute the query and put data into a result
$result = $this->sqlConn->query($sqlString);
//Copy result into a associative array
$resultArray = $result->fetch_all(MYSQLI_ASSOC);
//Copy result into a numeric array
$resultArray = $result->fetch_all(MYSQLI_NUM);
//Copy result into both a associative and numeric array
$resultArray = $result->fetch_all(MYSQLI_BOTH);
請務必參考您使用的框架的手冊。 fetch_assoc();以結合數組的形式提取結果行。如果你想獲取所有行,請使用while語句,如下所示:
$result = $c->query('SELECT user,host FROM mysql.user');
while ($row = $result->fetch_assoc()) {
printf("'%s'@'%s'\n", $row['user'], $row['host']);
'fetch_assoc()'只返回單個數組。 – Yash
當您執行'$ datos = $ result-> fetch_assoc();'時,您只會獲取第一條記錄。 – jeroen
也許'fetch_array'? – aldrin27