2011-05-30 52 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);