2

我收到错误:Invalid argument supplied for foreach()

这是我连接到数据库的类:

class dbMySql {

    static function Exec($query) {
        // open database
        $conn = mysql_connect('localhost','root','****');
        if($conn == false) {
            throw new Exception(mysql_connect_error());
    }
        mysql_select_db('data',$conn);

    $result = mysql_query($query,$conn);

        if(is_bool($result) && !$result) {
            $error = mysql_error($conn);
            mysql_close($conn);
            throw new Exception($error);
        }

        mysql_close($conn);

    return $result;
    }
}

我有这个代码:

echo '{ "results" : [ ';

$gettruck_result = dbMySql::Exec("SELECT  id, name, lat, lng FROM data)");
$result_array = array();

foreach($gettruck_result as $row) {

  $row_object = '{';
  $row_object .= '"id": "' . $row['id'] . '", ';
  $row_object .= '"name": "' . $row['name'] . '", ';
  $row_object .= '"lat": "' . $row['lat'] . '", ';
  $row_object .= '"lng": "' . $row['lng'] . '", ';
  $row_object .= '}';    
  $result_array[] = $row_object;
}

$result_str = implode(", ", $result_array);
echo $result_str;
echo " ] }";
?>

知道为什么我在 foreach 循环中出现错误吗?

4

2 回答 2

3

你必须更换:

foreach($gettruck_result as $row) {

... 和 ...

while($row = mysql_fetch_assoc($gettruck_result)) {
于 2012-06-16T08:57:33.047 回答
0

您已检查结果数组是否为空..

if(mysql_num_rows($gettruck_result)>0)
{
     foreach($gettruck_result as $row) {
      .
      .
     }
}
于 2012-06-16T09:39:53.813 回答