I wanted to insert data from an Android into a MySQL database. After inserting a record, I want to get the last insert id and retrieve the lastID value. Is it possible? How can I achieve this ? Any help would be appreciated.
addInformation(status, timeIn);
lastID =? // what should I write in order to get the last ID ?
public void addInformation(final String name, final String weather, final String date2, final String status, final String timeIn, final String timeOut) {
class AddInfo extends AsyncTask<String, Void, String> {
ProgressDialog loading;
@Override
protected void onPreExecute() {
super.onPreExecute();
loading = ProgressDialog.show(WorkDetailsTable.this, "Please Wait", null, true, true);
}
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
loading.dismiss();
Toast.makeText(getApplicationContext(),s, Toast.LENGTH_LONG).show();
//addWorkForce(Sub, NoP, NoH, Long.parseLong(s));
// addWorkDetails(results, Long.parseLong(s));
}
@Override
protected String doInBackground(String... params) {
HashMap<String, String> data = new HashMap<String, String>();
data.put(Config.KEY_USER_NAME, name);
data.put(Config.KEY_WEATHER, weather);
data.put(Config.KEY_DATE, date2);
data.put(Config.KEY_STATUS, status);
data.put(Config.KEY_TIMEIN, timeIn);
data.put(Config.KEY_TIMEOUT, timeOut);
RequestHandler rh = new RequestHandler();
String result = rh.sendPostRequest(Config.ADD_INFORMATION, data);
return result;
}
}
AddInfo ru = new AddInfo();
ru.execute(name, weather, date2, status, timeIn, timeOut);
}
ADD_INFORMATION.php
<?php
if($_SERVER['REQUEST_METHOD']=='POST'){
//Getting values
$status = $_POST['status'];
$timeIn = $_POST['timeIn'];
//Creating an sql query
$sql = "INSERT INTO information(status, time_in) VALUES ('$status', '$timeIn')";
//Importing our db connection script
require_once('dbConnect.php');
//Executing query to database
if(mysqli_query($con,$sql)){
echo 'Information Added Successfully';
$insertId=mysql_insert_id();
echo json_encode($insertId);
}else{
echo 'Could Not Add Information';
}
//Closing the database
mysqli_close($con);
}
?>
I want to get the $insertId and put into lastID