0

我有一个 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 设备运行应用程序时总是会出错

4

1 回答 1

2

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

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

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

于 2013-09-06T16:37:06.277 回答