2012-11-10 3 views
0

PHP에서 결과를 안드로이드로 반환하려고합니다.PHP로 데이터베이스에서 JSON 배열을 android로 되 돌리십시오.

나는 하나의 결과를 반환 할 수 있었지만 지금은 배열로 이것을 수행하는 방법을 알아 내는데 어려움을 겪고있는 여러 것들을 반환하려고합니다.

PHP 함수 : 그러나 잡 아래로

//SEARCH FOR PEOPLE 
    else if ($tag == 'searchPeople') { 

     $tower = $_POST['tower']; 

     $result = $db->searchForPeople($tower); 


    // check array has been created 
    if ($result != false) { 

     $response["success"] = 1; 

     $count = 0; 
     foreach($result as $row) { 

     $response[$count]["user"]["name"] = $row["name"]; 
     $response[$count]["user"]["email"] = $row["email"]; 

     $count++; 
     } 

     echo json_encode($response); 


     } else { 
     $response["error"] = 2; 
     $response["error_msg"] = "No users found"; 
     echo json_encode($response); 
    } 
    } 

     else { 
    echo "Invalid Request"; 
} 

내가 다시 안드로이드에서 정보를 얻기 위해 노력하고 있어요 : 난에 안드로이드에서 내 데이터를 POST의 index.php의

public function searchForPeople($tower) { 
    $uuid = uniqid('', true); 

    $result = mysql_query("SELECT * FROM users WHERE tower='$tower'") or die(mysql_error()); 
    $resultNo = mysql_num_rows($result); 

    // check for successful store 
    if ($result != null) { 

     //if just one result return it 
     if ($resultNo == 1) { 

      // return result 
      $resultSet[] = mysql_fetch_array($result); 
      return $resultSet; 

    //if more than one loop through 
    } else { 

     //add each row to an array 
     while($row = mysql_fetch_array($result)) { 
      $resultSet[] = $row; 
     } 
     return $resultSet; 
     } 

    } else { 
     return false; 
    } 
} 

제 그 오류는 0 값이 없다는 것을 의미합니다. PHP에서 json을 반환 한 방식에 문제가 있어야합니다.

JSONObject results = new JSONObject(resultsString); 
JSONObject json_row = results.getJSONObject("0"); 
JSONObject json_user = json_row.getJSONObject("user"); 

확실한 결과는 SQL 결과의 PHP 배열을 반환하는 데 있습니다. 아마 내가 $ resultSet 또는 $ response에 추가하기 위해 반복 할 때.

도움을 주시면 감사하겠습니다.

편집 :

는 여기에 내가 점점 오전 오류입니다 :

11-14 19:42:37.270: E/JSON(639): "[{\"uid\":\"4\",\"unique_id\":\"505efc638e0f48.78430999\",\"name\":\"fish\",\"email\":\"fish\",\"encrypted_password\":\"r\/Hb7uXrHN8bFuRoKlG8+Y5LdKFjM2QyZDUyYzQ1\",\"salt\":\"c3d2d52c45\",\"created_at\":\"2012-09-23 13:11:15\",\"updated_at\":\"2012-11-03 09:56:15\",\"location\":\"888\",\"tower\":\"IS\",\"base_location\":\"\",\"client_site\":\"\",\"graduate\":\"0\",\"location_updated\":\"0000-00-00 00:00:00\"}]" 
11-14 19:42:37.270: E/JSON Parser(639): Error parsing data org.json.JSONException: Value [{"uid":"4","unique_id":"505efc638e0f48.78430999","name":"fish","email":"fish","encrypted_password":"r/Hb7uXrHN8bFuRoKlG8+Y5LdKFjM2QyZDUyYzQ1","salt":"c3d2d52c45","created_at":"2012-09-23 13:11:15","updated_at":"2012-11-03 09:56:15","location":"888","tower":"IS","base_location":"","client_site":"","graduate":"0","location_updated":"0000-00-00 00:00:00"}] of type java.lang.String cannot be converted to JSONArray 

답변

0

내가 최근 아래와 루틴 유사한 사용. 결과가 하나이거나 많은 경우에도 항상 효과가 있습니다.

$dbuser = // user name; 
$dbpass = // password; 
$dbhost = // host name; 
$dbname = // database name; 

$sql = "SELECT * FROM users WHERE tower=" . $tower; 

try { 
$dbh = new PDO("mysql:host=$dbhost;dbname=$dbname;charset=utf8", $dbuser, $dbpass); 
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); 
$stmt = $dbh->query($sql); 
$results = $stmt->fetchAll(PDO::FETCH_OBJ); 
$dbh = null; 
echo '({"items":'. json_encode($results) .'});'; 
} catch(PDOException $e) { 
echo '{"error":{"text":'. $e->getMessage() .'}}'; 
} 
0

당신은 당신의 resultsString 그것이 어떻게 보이는지하고 예상 JSON 문자열이 있는지 여부를 확인하기 위해 Log를 디버깅 할 덤프해야합니다. 그런 다음 서버 또는 클라이언트에서 코드를 수정해야하는 위치를 확인할 수 있습니다.

다시 보내 주신 응답이 AFAICS 중첩 배열로 구성되어 있기 때문에 JSONObject.getJSONArray()도 살펴 보겠습니다.

0

난 당신이 PHP의 행을 당깁니다

mysql_fetch_assoc 

를 사용해야합니다 생각합니다. 그런 다음 결과가 Android로 돌아 가야 할 문자열에 json_encoded 될 준비가되었습니다.

그래서이 시도 :

function sqlToJSON($sql){ 
    $sth = mysql_query($sql); 

    //if this is an update or an insert nothing to return 
    if($sth === false || $sth === true){  

     return null; 
    }  

    $rows = array(); 
    while($r = mysql_fetch_assoc($sth)) { 
     $rows[] = $r; 
    } 
    return json_encode($rows); 
} 

당신은 어떤 추가 번역을 할 필요없이 자바 측 에 new JSONObject(res);를 통해이 방법의 결과를 실행할 수 있어야합니다 ... 나는 메모리에서 이런 말을 해요 따라서 100 % 맞지는 않을 수도 있지만 그렇지 않은 경우에는 매우 가깝습니다.

+0

고마워요. 실제로 결과 값 이상을 반환하지만 자바에서 반환되는 문자열을 구문 분석 할 때 JSONerror 예외가 발생합니다. 이것은 타임 스탬프 또는 빈 값과 같은 데이터베이스의 내 항목 때문일 수 있습니까? – EHarpham

+0

당신의 반환 가치가 실제로 무엇인지 보지 않고 말하기가 어렵습니다. 붙여 줄 수 있니? 또한, 당신이 말하는 예외가 정확히 무엇입니까? 내가 잘 모르겠다는 점은 JSON이 잘 형성되도록 전체 결과가 {그리고}로 싸여 있는지 여부입니다. –

+0

오류가 EDIT에 게시되었습니다.나는 이것을 여러 가지 방법으로 시도했다. addslashes를 포함하고 JSONArray 대신 JSONObject로 변환하지만, 아직 운이 없다. – EHarpham

관련 문제