2011-05-30 51 views
1

問題的簡化版本:PHP - 從查詢結果中獲取對象數組

所以我有這個查詢是在一個函數內。

$query = "SELECT * FROM users"; 
$result = mysql_query($query); 

我想如何使用mysql_fetch_object()從一行中獲取對象。

因爲最終我希望得到的對象數組我這樣做:

while ($a[] = mysql_fetch_object($result)) { // empty here } 

到底函數只是返回$ a。它工作得很好。

我的問題是,mysql_fetch_object將在最後返回一個NULL「行」(這是正常的,因爲結果結束,但我仍然將其分配給數組)。

關於如何以一種體面的方式做到這一點的任何想法?提前致謝。

回答

6

後,或者你也可以從while條件分配移至而身體像:

<?php 
while ($entry = mysql_fetch_object($result)) { 
    $a[] = $entry; 
} 
+0

簡單而好。謝謝。 – 2011-05-30 08:23:30

0

你可以只添加

array_pop($a); 

while

http://php.net/manual/en/function.array-pop.php

+0

一般不建議重複,而是因爲這將永遠存在,因爲這是在循環的退出條件,這是一個合理的解。我會添加一條評論,解釋爲什麼你是'array_pop'ing。 – 2011-05-30 07:51:49

+0

我會記住這個功能,有時可能會有用。 – 2011-05-30 08:30:35

3

mysql_fetch_object實際上返回0如果沒有更多行,則爲。我這樣做:

$a = array(); 
while (($row = mysql_fetch_object($result)) !== FALSE) { 
    $a[] = $row; 
} 
+0

!== FALSE在這裏是沒用的^^ – MatTheCat 2011-05-30 09:10:23

+0

我一直認爲這種類型檢查在PHP中處理布爾返回值時的良好實踐。在這種情況下,這並不重要,但它有很多其他的,這當然是。這是一個防禦性編程練習,IMO。 – 2011-06-01 09:28:10

+0

@MatTheCat吧。當它返回false時,循環停止。 – ShadeTreeDeveloper 2013-03-15 12:36:00

0

這個問題似乎是的how to fetch all the row of the result in php mysql?

//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);