从php检索JSON时出错 - Android

时间:2012-10-03 22:40:44

标签: php android mysql json

我正在使用我的Android应用程序一个php文件与我正在使用的mySql数据库进行通信。当我刚使用INSERT查询时,php工作得很好,但是当我添加SELECT查询时,它无法将JSON返回给我的应用程序。关键是在我向数据库添加一行后,我想返回新行的id。 id是int,带有自动增量。

这是我的PHP代码:

<?php

/*
* Following code will create a new product row
* All product details are read from HTTP Post Request
*/

// array for JSON response
$response = array();

// check for required fields
if (isset($_POST['lat']) && isset($_POST['lon']) && isset($_POST['alt'])) {

$name = $_POST['lat'];
$price = $_POST['lon'];
$description = $_POST['alt'];

// include db connect class
require_once __DIR__ . '/db_connect.php';

// connecting to db
$db = new DB_CONNECT();

// mysql inserting a new row
$result = mysql_query("INSERT INTO sits(lat, lon, alt) VALUES($name, $price, $description)");

// check if row inserted or not
if ($result) {
    // successfully inserted into database
    $response["success"] = 1;
    $response["message"] = "sit created.";
    $result2 = mysql_query("SELECT id FROM sits ORDER BY id DESC LIMIT 1")
    while($row = mysql_fetch_array($result2))
    {
       $response["id"]=$row['id'];
    }
    // echoing JSON response
    echo json_encode($response);
} else {
    // failed to insert row
    $response["success"] = 0;
    $response["message"] = "Oops! An error occurred.";

    // echoing JSON response
    echo json_encode($response);
}
} else {
// required field is missing
$response["success"] = 0;
$response["message"] = "Required field(s) is missing";

// echoing JSON response
echo json_encode($response);
}
?>

1 个答案:

答案 0 :(得分:1)

你肯定需要mysql_insert_id()。 SELECT查询是不必要的。文档声明:

  

返回值

     

上一次查询为AUTO_INCREMENT列生成的ID   success,如果前一个查询未生成AUTO_INCREMENT,则为0   value,如果没有建立MySQL连接,则为FALSE。

if ($result) {
    // successfully inserted into database
    $response["success"] = 1;
    $response["message"] = "sit created.";
    $response["id"] = mysql_insert_id();
    // echoing JSON response
    echo json_encode($response);
}