I am trying to insert multiple (1-50) entries from an Android application to an external Mysql database. I perfectly got a PHP script to work for single INSERT queries. But I am failing so far to make this work for a whole array of entries, most likely due to my limited understanding of PHP.
Android code:
List<NameValuePair> upload_array = new ArrayList<NameValuePair>();
upload_array.add(new BasicNameValuePair("mFirstname[0]", "FirstName 1"));
upload_array.add(new BasicNameValuePair("mFirstname[1]", "FirstName 2"));
upload_array.add(new BasicNameValuePair("mLastname[0]", "LastName 1"));
upload_array.add(new BasicNameValuePair("mLastname[1]", "LastName 2"));
upload_array.add(new BasicNameValuePair("mNickname[0]", "NickName 1"));
upload_array.add(new BasicNameValuePair("mNickname[1]", "NickName 2"));
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://url/script.php");
HttpResponse response = null;
try {
httppost.setEntity(new UrlEncodedFormEntity(upload_array));
response = httpclient.execute(httppost);
} catch (Exception e) {
e.printStackTrace();
}
And in PHP:
<?php
$connect = mysqli_connect("***","***","***", "***");
if(mysqli_connect_errno($connect))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
else
{
echo "success";
}
$query = mysqli_prepare("INSERT INTO `namelist` (`firstname`,`lastname`,`nickname`)
VALUES(?,?,?)");
$mFirstname = $_POST['mFirstname'];
$mLastname = $_POST['mLastname'];
$mNickname = $_POST['mNickname'];
foreach($mFirstname as $key as $key => $value) {
$query->bind_param('sss',$value["mFirstname"],$value["mLastname"],$value["mNickname"];
$query->execute();
}
mysqli_close($connect);
?>
Is the mistake happening in the Android part of the code already or does this PHP script just not read the data I sent properly? Any insight would be very welcome.
Ok, I made this work using a JSON Array. In case anyone has use for it, here's how it goes:
Android, create JSON String:
//Create JSON string start
String json_string ="{\"upload_fishes\":[";
//Repeat and loop this until all objects are added (and add try+catch)
JSONObject obj_new = new JSONObject();
obj_new.put("fish_id", your_looped_string_1[i]);
obj_new.put("fish_lat", your_looped_string_2[i]);
obj_new.put("fish_lon", your_looped_string_3[i]);
json_string = json_string + obj_new.toString() + ",";
//Close JSON string
json_string = json_string.substring(0, json_string.length()-1);
json_string += "]}";
Android send data to PHP (add try+catch):
HttpParams httpParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParams, TIMEOUT_MILLISEC);
HttpConnectionParams.setSoTimeout(httpParams, TIMEOUT_MILLISEC);
HttpClient client = new DefaultHttpClient(httpParams);
String url = "http://yourserver.com/script.php";
HttpPost request = new HttpPost(url);
request.setEntity(new ByteArrayEntity(json_string.getBytes("UTF8")));
request.setHeader("json", json_string);
HttpResponse response = client.execute(request);
Log.d("FISHY", response.getStatusLine().toString());
PHP script:
<?php
//CONNECT TO THE DATABASE
$DB_HOST = 'yourhost.com';
$DB_USER = 'user';
$DB_PASS = 'password';
$DB_NAME = "db_name";
$mysqli = new mysqli($DB_HOST, $DB_USER, $DB_PASS, $DB_NAME);
if(mysqli_connect_errno())
{
// echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
else
{
// echo "Connected to MySQL";
}
$postdata = file_get_contents("php://input");
$data = json_decode($postdata, true);
if (is_array($data['upload_fishes'])) {
foreach ($data['upload_fishes'] as $record) {
$fid = $record['fish_id'];
$flat = $record['fish_lat'];
$flon = $record['fish_lon'];
mysqli_query($mysqli,"INSERT INTO `fishes`(`fish_type_id`, `fish_lat`, `fish_lon`) VALUES ($fid, $flat, $flon)");
}
}
mysqli_close($mysqli);
?>
Related
I'm trying to store Arabic characters in a database on server. But when I add something it will be displayed as ???????????? in the database! I tried too add from my php to check if the problem from the php file, but it added the text correctly in database. So the error from android and json, how can I make the encoding of json to utf8 in android?
Here's my code:
class AddStories extends AsyncTask<String, String, String> {
protected String doInBackground(String... args) {
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("Caregiver_ID", ID));
params.add(new BasicNameValuePair("Title", "قصة"));
params.add(new BasicNameValuePair("Story", "قصتي بدأت عندما"));
JSONObject json = jsonParser.makeHttpRequest(url_add_story,"POST", params);
Log.d("Create Response", json.toString());
try {
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
suc=1;
sucess();
}
else {
suc=0;
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
}
PHP for adding:
<?php
header("Content-Type: text/html; charset=utf-8");
// array for JSON response
$response = array();
// check for required fields
if (isset($_POST['Caregiver_ID']) && isset($_POST['Title'])&& isset($_POST['Story'])) {
$Caregiver_ID = $_POST['Caregiver_ID'];
$Title = $_POST['Title'];
$Story = $_POST['Story'];
// include db connect class
require_once __DIR__ . '/db_connect.php';
// connecting to db
$db = new DB_CONNECT();
mysql_query("SET NAMES 'utf8'"); mysql_query('SET CHARACTER SET utf8');
// mysql inserting a new row
$result = mysql_query("INSERT INTO Stories(Caregiver_ID, Title, Story) VALUES('$Caregiver_ID', '$Title','$Story')");
// check if row inserted or not
if ($result) {
// successfully inserted into database
$response["success"] = 1;
$response["message"] = "glossary successfully created.";
// echoing JSON response
echo json_encode($response,JSON_UNESCAPED_UNICODE );
} 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 );
}
?>
Also when I tried to retrieve from android I got this for the text:
نةيىؤتيلالاؤتيلاارلابارابي-الالالتعا
while its retrieved correctly in php.
PHP code
<?php
header("Content-Type: text/html; charset=utf-8");
$response = array();
require_once __DIR__ . '/db_connect.php';
$db = new DB_CONNECT();
$result = mysql_query("SELECT *FROM Stories ") or die(mysql_error());
mysql_query("SET NAMES 'utf8'"); mysql_query('SET CHARACTER SET utf8');
if (mysql_num_rows($result) > 0) {
$response["story"] = array();
while ($row = mysql_fetch_array($result)) {
$story = array();
$story ["Caregiver_ID"] = $row["Caregiver_ID"];
$story ["Title"] = mb_convert_encoding($row["Title"],'HTML-ENTITIES','utf-8');
$story ["Story"] = mb_convert_encoding($row["Story"],'HTML-ENTITIES','utf-8');
array_push($response["story"], $story);
}
$response["success"] = 1;
echo json_encode($response);
} else {
// no products found
$response["success"] = 0;
$response["message"] = "No locations found";
// echo no users JSON
echo json_encode($response);
}
?>
Try below code in android
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try {
response = client.execute(httpGet);
HttpEntity entity = response.getEntity();
InputStream stream = entity.getContent();
byte[] buffer = new byte[1024];
int nread;
while ((nread = stream.read(buffer)) > 0) {
baos.write(buffer, 0, nread);
}
} catch (ClientProtocolException | IOException e) {
}
//Create a JSON from the String that was return.
JSONObject jsonObject = new JSONObject();
try {
String jsonText = new String(baos.toByteArray(), StandardCharsets.UTF_8);
jsonObject = new JSONObject(jsonText);
You have to put N before the columns which you need to add the Arabic text.
For example N'مختار'.
According to your code,you should change this line
$result = mysql_query("INSERT INTO Stories(Caregiver_ID, Title, Story) VALUES('$Caregiver_ID', '$Title','$Story')");
........
.....
...
to be
$result = mysql_query("INSERT INTO Stories(Caregiver_ID, Title, Story) VALUES('$Caregiver_ID', N'$Title',N'$Story')");
I am making an app wherein I fetch user data from the corresponding sql table using php.
<?php
$email = $_POST["email"];
#mysql_connect("localhost","root","root") or die(#mysql_error());
#mysql_select_db("dtbse") or die(#mysql_error());
$x = mysql_query("select * from dtbse where email = '$email' ") or die(#mysql_error());
$result = array();
while ($y=mysql_fetch_array($x)) {
echo $y["uname"]."<br>";
echo $y["gender"]."<br>";
echo $y["pass"]."<br>";
echo $y["address"]."<br>";
echo $y["email"]."<br>";
}
?>
Any help will be greatly apprecitated. I know this question has been a lot of times but I dont think there is something replicating this issue. Thanks.
Here is the code snippet responsible for fetching and parsing.
final ArrayList arr = new ArrayList();
arr.add(new BasicNameValuePair("email", uname));
try {
DefaultHttpClient httpclient = new DefaultHttpClient(new BasicHttpParams());
HttpPost httppost = new HttpPost("http://xxyoxx.esy.es/getDetails.php");
httppost.setEntity(new UrlEncodedFormEntity(arr));
HttpResponse hr = httpclient.execute(httppost);
HttpEntity ent = hr.getEntity();
is = ent.getContent();
Toast.makeText(getApplicationContext(),"1 wrk ",Toast.LENGTH_LONG).show();
} catch (Exception fl) {
Toast.makeText(getApplicationContext(),"First Try error "+fl,Toast.LENGTH_LONG).show();
}
/*// Depends on your web service
httppost.setHeader("Content-type", "application/json");*/
String result=null;
try {
// json is UTF-8 by default
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
result = sb.toString();
Toast.makeText(getApplicationContext(),"2 str\n "+result,Toast.LENGTH_LONG).show();
} catch (Exception sl) {
sl.printStackTrace();
Toast.makeText(getApplicationContext(),"2 err\n "+sl,Toast.LENGTH_LONG).show();
}
try{
String aa = "", b = "", c = "";
JSONArray ar = new JSONArray(result);
for (int i = 0; i < ar.length(); i++) {
JSONObject jo = ar.getJSONObject(i);
aa = jo.getString("uname");
b = jo.getString("address");
c = jo.getString("email");
}
nm.setText(aa);
addr.setText(b);
mail.setText(c);
Toast.makeText(getApplicationContext(),"3 wrk"+result,Toast.LENGTH_LONG).show();
}
catch (Exception tl){
Toast.makeText(getApplicationContext(),"3 err "+tl,Toast.LENGTH_LONG).show();
}
Strings separated by <br> are not a valid JSON array. PHP can create JSON strings using json_encode
If you need to read a JSON array in Android you need to echo a JSON array from PHP:
<?php
$email = $_POST["email"];
mysql_connect("localhost","root","root") or die(mysql_error());
mysql_select_db("dtbse") or die(mysql_error());
$x = mysql_query("select * from dtbse where email = '$email' ") or die(mysql_error());
$result = array();
$res=[];
while ($y=mysql_fetch_array($x)) {
$res[] = [
$y["uname"],
$y["gender"],
$y["pass"],
$y["address"],
$y["email"]
];
}
echo json_encode($res); //Make PHP return a valid JSON response
Also, the error suppression operators may hide valuable debug infomation which may help you diagnose other problems.
If you instead prefer to pass the JSON object to Java then you can do the following (simpler) thing.
<?php
$email = $_POST["email"];
mysql_connect("localhost","root","root") or die(mysql_error());
mysql_select_db("dtbse") or die(mysql_error());
$x = mysql_query("select * from dtbse where email = '$email' ") or die(mysql_error());
$result = array();
$res=[];
while ($y=mysql_fetch_array($x)) {
$res[] = $y;
}
echo json_encode($res); //Make PHP return a valid JSON response
I have an error as stated in the title when trying to read SQL and encode it back to android.
I have tried the following:
Verified the value of $androidIMEI by printing to log file, value is returned as expected.
Verified the output of $sql and the query is OK (including the $_POST['myIMEI_toString']) value from android.
Verified the value of $json array, 2 arrays are returned as the query returns 2 rows from SQL, OK.
Replacing
$androidIMEI = isset($_POST['myIMEI_toString']) ? $_POST['myIMEI_toString'] : '';
WITH
$androidIMEI = "000000000000000" //works fine but I want to get that programmatically.
Code:
Android (Send IMEI):
TelephonyManager mngr = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
myIMEI = mngr.getDeviceId();
myIMEI_toString = myIMEI.toString();
...............
protected String doInBackground(String... arg0) {
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("myIMEI_toString",myIMEI_toString));
try
{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://path_on_server/file.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
InputStreamReader ireader = new InputStreamReader(is);
BufferedReader bf = new BufferedReader(ireader);
sb = new StringBuilder();
String line = null;
while ((line = bf.readLine()) != null) {
sb.append(line);
}
Log.e("pass 1", "connection success ");
}
catch(Exception e)
{
System.out.println("Error catch");
}
return id;
}
Android (JSON):
try {
JSONObject jsonResponse = new JSONObject(jsonResult);
JSONArray jsonMainNode = jsonResponse.optJSONArray("myarray");
for (int i = 0; i < jsonMainNode.length(); i++) {
JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
name = jsonChildNode.getString("Request_Name");
number = jsonChildNode.getString("Request_Number");
username = jsonChildNode.getString("Request_Username");
status = jsonChildNode.getString("Status");
arrName.add(name);
arrNumber.add(number);
arrUsername.add(username);
arrStatus.add(status);
System.out.println("Name: "+name);
System.out.println("Number: "+number);
System.out.println("Username: "+username);
System.out.println("Status: "+status);
}
} catch (JSONException e) {
Log.i("Error Log: ", e.toString());
System.out.println("Error: "+e.toString());
Toast.makeText(getApplicationContext(), "Error" + e.toString(), Toast.LENGTH_SHORT).show();
}
PHP:
<?php
include 'config.php';
//$androidIMEI = "000000000000000";
$androidIMEI = isset($_POST['myIMEI_toString']) ? $_POST['myIMEI_toString'] : '';
//$f = fopen("log.txt", "w");
//fwrite($f, print_r($androidIMEI, true));
//fclose($f);
$con=mysql_connect("$servername", "$username", "$password")or die("cannot connect");
mysql_select_db("$dbname")or die("cannot select DB");
$sql = "SELECT * from users WHERE Request='0' AND IMEI = '$androidIMEI' ";
$result = mysql_query($sql);
$json = array();
if(mysql_num_rows($result)){
while($row=mysql_fetch_assoc($result)){
$json['myarray'][]=$row;
}
}
else
{
//$error = "Error selecting record: " . $conn->error " ";
//$f = fopen("$error.txt", "w");
//fwrite($f, print_r($error, true));
//fclose($f);
}
$f = fopen("log.txt", "w");
fwrite($f, print_r($sql, true));
fclose($f);
mysql_close($con);
echo json_encode($json);
?>
Logcat Error:
org.json.JSONException: Value [] of type org.json.JSONarray cannot be converted to JSONObject
(i have asked this question before but will try again with more information)
I am trying to make a HttpPost from my app to a php script, which will then insert data to a remote database. I'm not getting any runtime errors, but the data never gets inserted into my remote database.
Code:
public class InsertResult extends AsyncTask<String, String, String>
{
#Override
protected String doInBackground(String... arg0)
{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.<myDomain>.co.za/insertTeamResultwithCode.php");
try
{
ArrayList<NameValuePair> nameValues = new ArrayList<NameValuePair>(10);
nameValues.add(new BasicNameValuePair("Code", password));
nameValues.add(new BasicNameValuePair("Section", section));
nameValues.add(new BasicNameValuePair("Gender", gender));
nameValues.add(new BasicNameValuePair("WinningTeam", newResult.getWinningTeam()));
nameValues.add(new BasicNameValuePair("LosingTeam", newResult.getLosingTeam()));
nameValues.add(new BasicNameValuePair("FixtureD", newResult.getDate()));
nameValues.add(new BasicNameValuePair("FixtureT", newResult.getTime()));
nameValues.add(new BasicNameValuePair("Venue", newResult.getVenue()));
nameValues.add(new BasicNameValuePair("Court", newResult.getCourt()));
nameValues.add(new BasicNameValuePair("Texts", newResult.getText()));
httppost.setEntity(new UrlEncodedFormEntity(nameValues));
HttpResponse response = httpclient.execute(httppost);
}
catch (ClientProtocolException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result)
{
GoToJarvisDashboard();
}
}
And PhP script:
<?php
//Code verifications
$Code = $_GET['Code'];
//Variables for SQL INSERT
$Section = $_GET['Section'];
$Gender = $_GET['Gender'];
$WinningTeam = $_GET['WinningTeam'];
$LosingTeam = $_GET['LosingTeam'];
$FixtureD = $_GET['FixtureD'];
$FixtureT = $_GET['FixtureT'];
$Venue = $_GET['Venue'];
$Court = $_GET['Court'];
$Texts = $_GET['Texts'];
$SetsWon = $_GET['SetsWon'];
$SetsLost = $_GET['SetsLost'];
$Winner_Score = $_GET['Winner_Score'];
$Loser_Score = $_GET['Loser_Score'];
$dbname = '<dbName>';
$dbuser = '<user>';
$dbpass = '<password>';
$dbhost = '<host>t';
$connect = mysqli_connect($dbhost, $dbuser, $dbpass, $dbname) or die ("Unable to Connect to '$dbhost'");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$SQL = "SELECT * FROM squasdlw_db1.validationCodes WHERE Code = '$Code'";
$codeValid = mysqli_query($connect, $SQL) or die (mysqli_error($connect));
$response["no"] = array();
if (mysqli_num_rows($codeValid) > 0)
{
echo "Code is valid\n\n";
//Insert Result
$query = "INSERT INTO squasdlw_db1.jarvisTeamResults (Section,Gender,WinningTeam,LosingTeam,FixtureD,FixtureT,Venue,Court,Texts,SetsWon,SetsLost,Winner_Score,Loser_Score) VALUES('$Section','$Gender','$WinningTeam','$LosingTeam','$FixtureD','$FixtureT','$Venue','$Court','$Texts','$SetsWon','$SetsLost','$Winner_Score','$Loser_Score')";
$result = mysqli_query($connect, $query) or die (mysqli_error($connect));
echo "Result successfully submitted to Jarvis Remote Database: Table -> jarvisTeamResults\n\n" ;
//Update Winner on jarvisLogs
$query = "UPDATE squasdlw_db1.jarvisLogs SET Points = Points + '$Winner_Score', Played = Played + 1, Won = Won + 1 WHERE Gender = '$Gender' AND Section = '$Section' AND Team = '$WinningTeam'";
$result = mysqli_query($connect, $query) or die (mysqli_error($connect));
echo "Log update for '$WinningTeam': Table -> jarvisLogs\n\n";
//Update Winner on jarvisLogs
$query = "UPDATE squasdlw_db1.jarvisLogs SET Points = Points + '$Loser_Score', Played = Played + 1, Lost = Lost + 1 WHERE Gender = '$Gender' AND Section = '$Section' AND Team = '$LosingTeam'";
$result = mysqli_query($connect, $query) or die (mysqli_error($connect));
echo "Log update for '$LosingTeam': Table -> jarvisLogs\n\n";
$response["isValid"] = true;
echo json_encode($response);
}
else
{
$response["isValid"] = false;
echo "The code is not valid\n";
echo json_encode($response);
}
mysqli_close($connect);
?>
Whats even weirder is that if I try this in a web browser, it works fine and the data does get added to the remote database-
http://www.<myDomain>.co.za/insertTeamResultwithCode.php?Code=<password>&Section=A&Gender=Men&WinningTeam=NW&LosingTeam=KZN&FixtureD=2015-05-25&FixtureT=09:00:00&Venue=Puk&Court=6&Texts=Andrew%20(NW)%20beat%20Kevin%20(WP)%203-1&SetsWon=15&SetsLost=5&Winner_Score=15&Loser_Score=5
Please help out, I have no idea what is going wrong because it does not create runtime errors? I am about to go crazy...
You are doing an HttpPost so you should get your data via POST and not GET
//Code verifications
$Code = $_POST['Code'];
//Variables for SQL INSERT
$Section = $_POST['Section'];
$Gender = $_POST['Gender'];
$WinningTeam = $_POST['WinningTeam'];
$LosingTeam = $_POST['LosingTeam'];
$FixtureD = $_POST['FixtureD'];
$FixtureT = $_POST['FixtureT'];
$Venue = $_POST['Venue'];
$Court = $_POST['Court'];
$Texts = $_POST['Texts'];
$SetsWon = $_POST['SetsWon'];
$SetsLost = $_POST['SetsLost'];
$Winner_Score = $_POST['Winner_Score'];
$Loser_Score = $_POST['Loser_Score'];
Or change your android code to make GET requests :
HttpGet httpget = new HttpGet("http://www.example.com/insertTeamResultwithCode.php");
You are sending POST in android BUT you are expecting GET in php which are not the same.
Change the $_GET to $_POST and it will work.
Here a post that will tell you difference between then
Here another with some more details
This is my java code
public void login() {
try {
httpclient = new DefaultHttpClient();
httppost = new HttpPost("http://192.168.0.104/rocket/assign_job.php"); // make sure the url is correct.
//add your data
nameValuePairs = new ArrayList<NameValuePair>(1);
// Always use the same variable name for posting i.e the android side variable name and php side variable name should be similar,
//int smsNum = Integer.parseInt(smsCode.getText().toString());
nameValuePairs.add(new BasicNameValuePair("smsCode", smsCode));// $Edittext_value = $_POST['Edittext_value'];
//nameValuePairs.add(new BasicNameValuePair("userName", rocketName));
Log.d("smsCode ===", smsCode);
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
//Execute HTTP Post Request
//response=httpclient.execute(httppost);
ResponseHandler<String> responseHandler = new BasicResponseHandler();
final String response = httpclient.execute(httppost, responseHandler);
runOnUiThread(new Runnable() {
public void run() {
Log.d("PHP Response: ", response);
pDialog.dismiss();
}
});
if (response.equalsIgnoreCase("success")) {
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(UserPage.this, "Job Assigned", Toast.LENGTH_SHORT).show();
}
});
} else {
showAlert();//testing bitbuckettt
}
} catch (Exception e) {
pDialog.dismiss();
System.out.println("Exception : " + e.getMessage());
}
}
This is my PHP Code:
<?php
// include db connect class
require_once __DIR__ . '/db_connect.php';
// connecting to db
$db = new DB_CONNECT();
if(isset($_POST['smsCode'])){
$smsCode = $_POST['smsCode'];
$query_search = "SELECT * FROM confirmedrequest WHERE smsCode='".$smsCode."'";
$query_exec = mysqli_query($db->getConnection(),$query_search) or die(mysqli_error($db->getConnection()));
$row = mysqli_num_rows($query_exec);
if($row == 0){
echo "failed";
}else{
echo "success";
$rocketName = mysqli_real_escape_string($db->getConnection(),$_POST["userName"]);
$sql_update = "UPDATE confirmedrequest SET jobTakenBy = '$rocketName' WHERE smsCode = $smsCode ";
$sql_exec = mysqli_query($db->getConnection(),$sql_update) or die(mysqli_error($db->getConnection()));
}
}else{
echo "Empty code";
}
?>
The PHP Response in logcat is always failed even though the code matches. I have tried to debug it for several hours but still cant solve. All I want is to run the code below (response.equalsIgnoreCase("success")) when the code matches.
You have to set the headers in order to the response to be formatted in a correct way:
$db = new DB_CONNECT();
if(isset($_POST['smsCode'])){
$smsCode = $_POST['smsCode'];
$query_search = "SELECT * FROM confirmedrequest WHERE smsCode='".$smsCode."'";
$query_exec = mysqli_query($db->getConnection(),$query_search) or die(mysqli_error($db->getConnection()));
$row = mysqli_num_rows($query_exec);
if($row == 0){
http_response_code(500);
echo "failed";
}else{
http_response_code(200);
echo "success";
$rocketName = mysqli_real_escape_string($db->getConnection(),$_POST["userName"]);
$sql_update = "UPDATE confirmedrequest SET jobTakenBy = '$rocketName' WHERE smsCode = $smsCode ";
$sql_exec = mysqli_query($db->getConnection(),$sql_update) or die(mysqli_error($db->getConnection()));
}
}else{
http_response_code(400);
echo "Empty code";
}