使用mysql_fetch_array()函数捕获多行结果

时间:2013-09-06 16:30:17

标签: php android mysql sql json

我有一个php函数,它从mySQL数据库中捕获一个地方的坐标并返回结果:

public function getCoordinatesByName($name) {
        $result = mysql_query("SELECT * FROM places WHERE name = '$name'") or die(mysql_error());
        // check for result 
        $no_of_rows = mysql_num_rows($result);
        if ($no_of_rows > 0) {
            $result = mysql_fetch_array($result);
            return $result;
        } else {
            // user not found
            return false;
        }
    } 

此函数在index.php中用于捕获结果并通过JSON将其发送到Android设备:

$place = $db->getCoordinatesByName($name);
if ($place != false) {
    // user found
    // echo json with success = 1

    $response["success"] = 1;
    $response["place"]["H"] = $place["H"];
    $response["place"]["V"] = $place["V"];
    $response["place"]["placeid"] = $place["placeid"];
    $response["place"]["name"] = $place["name"];
    $response["place"]["type"] = $place["type"];
    $response["place"]["note"] = $place["note"];
    $response["place"]["discription"] = $place["discription"];
    //$response["place"]["created_at"] = $user["created_at"];
    //$response["place"]["updated_at"] = $user["updated_at"];
    echo json_encode($response);
}

现在我想立刻发送所有地方的所有坐标,我创建了一个名为getCoordinates的函数:

 public function getCoordinates($name) {
        $result = mysql_query("SELECT * FROM places") or die(mysql_error());
        // check for result 
        $no_of_rows = mysql_num_rows($result);
        if ($no_of_rows > 0) {
            $result = mysql_fetch_array($result);
            return $result;
        } else {
            // user not found
            return false;
        }
    }

然后我以这种方式在index.php中使用它:

 $place = $db->getCoordinates($name);
 if ($place != false) {
     for ($i = 1;$i = count($place); $i++ ) {
         // user found
         // echo json with success = 1
         $response[$i]["success"] = 1;
         $response[$i]["place"]["H"] = $place[$i]["H"];
         $response[$i]["place"]["V"] = $place[$i]["V"];
         $response[$i]["place"]["placeid"] = $place[$i]["placeid"];
         $response[$i]["place"]["name"] = $place[$i]["name"];
         $response[$i]["place"]["type"] = $place[$i]["type"];
         $response[$i]["place"]["note"] = $place[$i]["note"];
         //$response["place"]["created_at"] = $user["created_at"];
         //$response["place"]["updated_at"] = $user["updated_at"];
     }
     echo json_encode($response);
 } 

我认为有些事情是不对的,因为当我从Android设备运行应用程序时,我总是会遇到错误

1 个答案:

答案 0 :(得分:2)

mysql_fetch_array()(及其堂兄_assoc_object)会返回一个 ROW 数据。它们不会获取整个查询结果。您需要构建一个行数组,然后返回:

$data = array();
while($row = mysql_fetch_array($result)) {
   $data[] = $row;
}
return $data;

然后你将得到你可以迭代的数组。