PHP - 从查询结果中获取对象数组

时间:2011-05-30 07:42:01

标签: php mysql arrays object

问题的简化版本:

所以我有一个函数内的查询。

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

我想如何使用mysql_fetch_object()从一行中获取对象。

因为最后我想得到一个对象数组,我这样做:

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

最后,该函数返回$ a。它的工作原理几乎没有。

我的问题是mysql_fetch_object最后会返回一个NULL“行”(这是正常的,因为结果已经结束,但我仍然将它分配给数组)。

有关如何以体面的方式做到这一点的任何想法?提前谢谢。

4 个答案:

答案 0 :(得分:8)

或者您可以将分配从while条件移动到while主体,如:

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

答案 1 :(得分:3)

如果没有更多行,

mysql_fetch_object实际返回FALSE。我会这样做:

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

答案 2 :(得分:0)

您只需添加

即可
array_pop($a);

while

之后

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

答案 3 :(得分: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);