Reputation: 187
I'm using for my android app a php file to communicate with the mySql DB i'm using. The php worked great when i just used the INSERT query, but when i added the SELECT query it just failed to return the JSON back to my app. The point is that after i add a row to the database i want to return the id of the new row. the id is int with auto-increment.
Here's my PHP code:
<?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);
}
?>
Upvotes: 1
Views: 989
Reputation: 11080
You definitely need mysql_insert_id() for that. A SELECT query is unnecessary. The docs state:
Return Values
The ID generated for an AUTO_INCREMENT column by the previous query on success, 0 if the previous query does not generate an AUTO_INCREMENT value, or FALSE if no MySQL connection was established.
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);
}
Upvotes: 1