Getting a response from a php script call - php

I have an app that sends some information via POST to a php script in a server. It uses Asynchttpclient. How can I also receive a reply back from the server (via json?)? Please help.
This is my php script
if($_POST["mode"]=="newuser"){
//$gcmRegID = $_GET["shareRegId"];
$gcmRegID = $_POST["regID"];
$gcmUserName = $_POST["userName"];
$gcmFolderName = $_POST["folderName"];
$gcmDate = date("d/m/y");
$conn = new mysqli($servername, $username, $password, $dbname);
if($conn->connect_error){
die("Connection failed: " . $conn->connect_error);
}
$in_user = "user";
$in_password = "NULL";
$in_email = "NULL";
$in_dob = "NULL";
$in_role = "user";
$in_datejoined = "0000-00-00";
$foldername = "NULL";
$sql = "INSERT INTO user(password,regid,name,email,phone,dob,role,datejoined,foldername) VALUES('$in_password','$gcmRegID','$gcmUserName','$in_email','$in_phone','$in_dob','$in_role','$gcmDate','$foldername')";
$substringtitle = substr($gcmRegID,-7);
$combined = $gcmUserName."_".$substringtitle;
if($conn->query($sql)===TRUE){
mkdir("./users/".$gcmFolderName);
$newfoldername = "./users/".$gcmFolderName;
$updatequery = "UPDATE user SET foldername='$newfoldername' WHERE name='$gcmUserName'";
$returnfield = array(
'foldername' => $newfoldername
);
header('Content-type: application/json');
echo json_encode(array('returnfield'=>$returnfield));
if($conn->query($updatequery)===TRUE){
echo "folder updated";
}
//echo "Folder created!";
//}
echo "New record created successfully";
}else{
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
echo "Done!";
exit;
}
Android code
//store in the file server (PHP)
private void storeREG(final String registerID,String userName,String folderName){
pg.show();
params.put("regID", registerID);
params.put("userName",userName);
params.put("folderName", folderName);
params.put("mode","newuser");
Log.d("STORE","STORE");
//Make RESTful webservice call
AsyncHttpClient client = new AsyncHttpClient();
client.post(AppConstants.SERVER_URL, params, new AsyncHttpResponseHandler() {
#Override
public void onSuccess(String content) {
pg.hide();
if (pg != null) {
pg.dismiss();
}
Toast.makeText(applicationCtx, "ID sharing successful", Toast.LENGTH_LONG).show();
Intent home = new Intent(applicationCtx, HomeActivity.class);
home.putExtra("regID", registerID);
Log.d("REGID", registerID);
startActivity(home);
finish();
}
#Override
public void onFailure(int statusCode, Throwable error, String content) {
pg.hide();
if (pg != null) {
pg.dismiss();
}
Log.d("ERRORTHROW", error.toString());
if (statusCode == 404) {
Toast.makeText(applicationCtx, "Requested resource not found", Toast.LENGTH_LONG).show();
} else if (statusCode == 500) {
Toast.makeText(applicationCtx, "Something went wrong at the server", Toast.LENGTH_LONG).show();
} else {
Log.d("SHOWME", String.valueOf(statusCode));
Toast.makeText(applicationCtx, "Unexpected error occurred", Toast.LENGTH_LONG).show();
}
}
});
}
Hopefully I can get help with this.

You may try to revise your PHP Code. Below is a well-commented sample code to get you started:
<?php
// EXPLICITLY INSTRUCT THE HEADER ABOUT THE CONTENT TYPE. HERE - JSON
header('Content-type: application/json');
if($_POST["mode"]=="newuser"){
$gcmRegID = htmlspecialchars(trim($_POST["regID"]));
$gcmUserName = htmlspecialchars(trim($_POST["userName"]));
$gcmFolderName = htmlspecialchars(trim($_POST["folderName"]));
$gcmDate = date("d/m/y");
// I WOULD STRONGLY SUGGEST YOU USE PDO FOR YOUR DATABASE TRANSACTIONS:
// HERE'S HOW:
//DATABASE CONNECTION CONFIGURATION:
defined("HOST") or define("HOST", "localhost"); //REPLACE WITH YOUR DB-HOST
defined("DBASE") or define("DBASE", "database"); //REPLACE WITH YOUR DB NAME
defined("USER") or define("USER", "root"); //REPLACE WITH YOUR DB-USER
defined("PASS") or define("PASS", "root"); //REPLACE WITH YOUR DB-PASS
// ESTABLISH A CONNECTION AND DO YOUR WORK WITHIN A TRY-CATCH BLOCK...
try {
$dbh = new PDO('mysql:host='.HOST.';dbname='. DBASE,USER,PASS);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// HERE: ALL YOUR BUSINESS LOGIC...
$in_user = "user";
$in_password = "NULL";
$in_email = "NULL";
$in_phone = "NULL";
$in_dob = "NULL";
$in_role = "user";
$in_dateJoined = "0000-00-00";
$folderName = "NULL";
$insertSQL = "INSERT INTO user(`password`, `regid`, `name`, `email`, `phone`, `dob`, `role`, `datejoined`, `foldername`) ";
$insertSQL .= " VALUES(:inPassword, :gcmRegID, :gcmUserName, :inEmail, :inPhone, :inDOB, :inRole, :gcmDate, :folderName)";
$arrInsertData = array(
'inPassword' => $in_password,
'gcmRegID' => $gcmRegID,
'gcmUserName' => $gcmUserName,
'inEmail' => $in_email,
'inPhone' => $in_phone,
'inDOB' => $in_dob,
'inRole' => $in_role,
'gcmDate' => $gcmDate,
'folderName' => $folderName
);
// PREPARE THE INSERT QUERY:
$insertStmt = $dbh->prepare($insertSQL);
// INSERT THE NEW ROW:
$insertStmt->execute($arrInsertData);
// OBTAIN THE ID OF THE INSERTED ROW TO BE USED AS SUFFIX FOR YOUR USER FOLDER
$id = $dbh->lastInsertId();
// WHAT HAPPENS WHEN 2 USERS HAVE THE SAME USERNAME??? DID YOU THINK ABOUT THAT?
// TO CIRCUMVENT THIS ISSUE; I WOULD SUGGEST FIRST TO INSERT THE DATA TO THE DATABASE...
// THEN USE THE ID AS A SUFFIX TO MAKE EACH USER DIRECTORY UNIQUE & THAT IS THE APPROACH TAKEN HERE THOUGH...
// NOW YOU CAN CREATE YOUR FOLDER USING THIS ID: $id
// LIKE THIS; 2 USERS WITH USERNAME "android_user" CAN HAVE 2 DIFFERENT FOLDERS LIKE SO: "android_user_97" & "android_user_102"
$userDirectory = "./users/" . $gcmFolderName . "_" . $id;
mkdir($userDirectory);
// DID IT OCCUR TO YOU THAT 2 USERS MIGHT HAVE THE SAME USERNAME IN WHICH CASE MYSQL (INSTEAD OF YOU) HAS TO DECIDE WHICH USER TO UPDATE?
// THAT IS WHY DATABASE TABLES ARE DESIGNED TO HAVE UNIQUE IDENTIFIERS LIKE UUID OR ID OR UID OR ANY TOKEN TO MAKE EACH ROW UNIQUE...
// WE ARE ADOPTING THIS APPROACH IN THE UPDATE QUERY... THAT IS: WE UPDATE THE ROW USING THE ID ABOVE... ASSUMING THAT IS A UNIQUE COLUMN THOUGH.
$updateSQL = "UPDATE user SET foldername=:newDirName WHERE id=:ID";
// NOW UPDATE THE ROW TO TAKE INTO ACCOUNT THE UNIQUE USER-DIRECTORY (USING THE ID AS THE KEY)
$arrUpdateData = array(
'newDirName' => $userDirectory,
'ID' => $id // THIS ASSUMES THAT THE PRIMARY KEY OF YOUR TABLE IS CALLED id OTHERWISE USE THE APPROPRIATE KEY NAME: EG: reg_id OR WHATEVER
);
// PREPARE THE UPDATE QUERY:
$insertStmt = $dbh->prepare($updateSQL);
// UPDATE THE NEWLY CREATED ROW:
$insertStmt->execute($arrUpdateData);
// BUILD THE RESPONSE JSON DATA
$arrResponse = array(
'folderName' => $userDirectory,
'id' => $id,
);
// SEND THE RESPONSE AS JSON IF ALL WORKS FINE TILL HERE...
// THAT MEANS: SEND THE DATA IN $arrResponse AND TERMINATE THE SCRIPT - THE JOB IS DONE.
// NO NEED FOR ALL THOSE ECHO STATEMENTS AS THE YOU ARE EXPLICITLY SENDING BACK JSON DATA.
die( json_encode($arrResponse) );
}catch(PDOException $e){
// IF THERE WAS ANY KIND OF PDO ERROR, SEND IT BACK ANYWAYS - BUT ALSO AS JSON:
$arrResponse = array(
'error' => $e->getMessage()
);
die( json_encode($arrResponse) );
}
}

I can't test the code right now (sorry), but I think it should be something like this:
try {
RequestParams rParams = new RequestParams();
rParams.put("example", "example"); // POST
AsyncHttpClient client = new AsyncHttpClient();
client.get(pageURL, rParams, new JsonHttpResponseHandler() {
#Override
public void onSuccess(JSONArray jsonArray) {
super.onSuccess(jsonArray);
//process JSON Array
}
#Override
public void onFailure(Throwable throwable, JSONArray jsonArray) {
super.onFailure(throwable, jsonArray);
Log.d(TAG, "error", throwable);
}
});
} catch (Exception e) {
Log.d(TAG, "exception", e);
}
Otherwise I made a very light WebClient, you may want to give it a shot:
https://github.com/omaflak/WebClient
This is a short sample:
WebClient client = new WebClient();
client.setOnRequestListener(new OnRequestListener() {
#Override
public void onRequest(String response, int requestID) {
Log.e(TAG, response);
}
#Override
public void onError(int error_code, String message) {
Log.e(TAG, message);
}
});
Pair p = new Pair("field1", "value1");
Pair p2 = new Pair("field2", "value2");
client.requestAsync("http://your-api.com", WebClient.POST, Arrays.asList(p, p2), 1);
// requestAsync(String url, String method, List<Pair<String, String>> postData, int requestID)
To use it, simply add to your dependencies:
compile 'me.aflak.libraries:webclient:1.0'

Related

android uploading empty image to the host using php

I'm trying to upload a photo from an android device to host using PHP and base 64, bitmap ; but it uploads two empty images (it uploads two times) can't figure out why, any help or alternative way?
I'm uploading the photo in a register layout so I tried just inserting the photo without anything else, and I tried using another hosting service but unfortunately, nothing worked.
the name of the empty photo is inserted in the database yet in the file manager it's an empty photo
the php code;
<?php
// array for JSON response
$response = array();
$user_image= $_POST['user_image'];
$user_name= $_POST['user_name'];
$user_email= $_POST['user_email'];
$user_un= $_POST['user_un'];
$user_pass= $_POST['user_pass'];
$servername = "...";
$username = "...";
$password = "...";
$dbname = "...";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
$conn->set_charset("utf8");
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}else{
$ra=rand(0,20000);
$rn=rand(0,40000);
$rd=rand(0,60000);
$imgname = "pl".$ra.$rn.$rd.".jpeg";
$decoding=base64_decode("$user_image");
file_put_contents("images/".$imgname,$decoding);
$sql = "INSERT INTO Users (user_name,user_email,user_un,user_pass,user_image)
VALUES ('$user_name','$user_email','$user_un','$user_pass','$imgname')";
if ($conn->query($sql) === TRUE) {
$UserId = $conn->insert_id;
$response['dishs'] = array();
$hobbie['status'] = "ok";
$hobbie['result'] = "Welcome";
// push single dishinto final response array
array_push($response['dishs'],$hobbie);
// echoing JSON response
echo json_encode($response);
} else {
// echo "Error: " . $sql . "" . $conn->error;
$response['dishs'] = array();
// failed to insert row
$hobbie['status'] = "no";
$hobbie['result'] = "Error: " . $sql . "" . $conn->error;
array_push($response['dishs'],$hobbie);
// echo no users JSON
echo json_encode($response);
}
}
$conn->close();
?>
the kotlin code
these are defined in the head of the class
"class RegisterPage :Fragment() {
var encodImg = ""
var bitmap: Bitmap? = null
......
"
sending this to the host
"... val params = HashMap<String, String>()
params["user_image"] = encodImg
...
"
the way i choose the photo from gallery and encrypt
private fun startGallery() {
val galleryIntent = Intent(Intent.ACTION_GET_CONTENT)
galleryIntent.type = "image/*"
if (galleryIntent.resolveActivity(activity!!.packageManager) != null) {
startActivityForResult(galleryIntent, 1000)
}
}
override fun onActivityResult(requestCode: Int, resultCode: Int, i: Intent?) {
super.onActivityResult(requestCode, resultCode, i)
if (resultCode == Activity.RESULT_OK) {
val uri: Uri? = i!!.data
change_profile_photo.setImageURI(uri)
manageImageFromUri(i.data!!)
} else {
Toast.makeText(activity, "Error", Toast.LENGTH_LONG).show()
}
}
private fun manageImageFromUri(imageUri: Uri) {
val baos = ByteArrayOutputStream()
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
Snackbar.make(view!!, "ERROR", Snackbar.LENGTH_LONG)
} else {
bitmap = MediaStore.Images.Media.getBitmap(activity?.contentResolver, imageUri)
bitmap!!.compress(Bitmap.CompressFormat.JPEG, 100, baos)
val b = baos.toByteArray()
encodImg = Base64.encodeToString(b, Base64.DEFAULT)
}
}
}

how to view result of php script on android text view

I want to get the result of a PHP script to display on Android Textview using retrofit I was able to send data in an edit text to the database doing something like this
This is for the post method
InstituteService instituteService = ApiClient.getApiClient(getApplicationContext()).create(InstituteService.class);
Call<ServiceResponse> calRegStudent = instituteService.UploadStudentsRecord(Surname,Firstname,Othername,Address,Age,Sex,Parentemail,Sclass,Regno,Tagno,Rollcallno,L_Finger1,L_Finger2,R_Finger1,R_Finger2,District_code,Zone_code,School_code);
calRegStudent.enqueue(new Callback<ServiceResponse>() {
#Override
public void onResponse(Call<ServiceResponse> call, Response<ServiceResponse> response) {
if(response.body() != null)
{
ServiceResponse rr= response.body();
if(rr.getStatus().contentEquals("1"))
{
Toast.makeText(MainActivity.this,"Data Submit Successfully", Toast.LENGTH_LONG).show();
ClearEditTextAfterDoneTask();
}
else
{
Toast.makeText(MainActivity.this,"Error", Toast.LENGTH_LONG).show();
}
The code for the get Method
InstituteService instituteService = ApiClient.getApiClient(getApplicationContext()).create(InstituteService.class);
Call<ServiceResponse> calRegStudent = instituteService.StudentGetRecord(Parentemail);
calRegStudent.enqueue(new Callback<ServiceResponse>() {
#Override
public void onResponse(Call<ServiceResponse> call, Response<ServiceResponse> response) {
if(response.body() != null)
{
ServiceResponse rr= response.body();
if(rr.getStatus().contentEquals("1"))
{
Toast.makeText(MainActivity.this,"Successfully", Toast.LENGTH_LONG).show();
ClearEditTextAfterDoneTask();
}
else
{
Toast.makeText(MainActivity.this,"Error", Toast.LENGTH_LONG).show();
}
I can only send the field needed to make the query but I have no idea how to display the result.
This the PHP script of the get method I am working on
<?php
//Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
//Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$parentemail=htmlspecialchars( $_GET["parentemail"]);
$sql = "SELECT surname,firstname,othername,rollcallno FROM studentTable WHERE parentemail='$parentemail';";
$result = mysqli_query($conn, $sql);
if (mysqli_query($conn, $sql)) {
echo(json_encode(array('Message'=>"New record created successfully",'Status'=>1)));
//echo "New record created successfully";
} else {
echo(json_encode(array('Message'=>mysql_error($conn),'Status'=>0)));
//echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
mysqli_close($conn);
?>
This is the InstituteService
package com.ainakay.studentapp;
import java.util.List;
import retrofit2.Call;
import retrofit2.http.Body;
import retrofit2.http.Field;
import retrofit2.http.FormUrlEncoded;
import retrofit2.http.GET;
import retrofit2.http.Header;
import retrofit2.http.POST;
public interface InstituteService {
#FormUrlEncoded
#POST("insertin.php")
Call<ServiceResponse> UploadStudentsRecord(#Field("surname") String surname,#Field("firstname") String firstname,
#Field("othername") String othername,#Field("address") String address,
#Field("age") String age,#Field("sex") String sex,#Field("parentemail") String parentemail,
#Field("sclass") String sclass,#Field("regno") String regno,
#Field("tagno") String tagno,#Field("rollcallno") String rollcallno,
#Field("l_Finger1") String l_Finger1,#Field("l_Finger2") String l_Finger2,
#Field("r_Finger1") String r_Finger1,#Field("r_Finger2") String r_Finger2,
#Field("district_code") String district_code,#Field("zone_code") String zone_code,#Field("school_code") String school_code);
#FormUrlEncoded
#GET("parentgetstudent.php")
Call<ServiceResponse> StudentGetRecord(#Field("parentemail")String parentemail);
}
Please am fairly new to android development will appreciate any sort of help
First, for the server part, you have to return all the fields that you need to show in Android:
$result = mysqli_query($conn, $sql);
if ($result) {
$row = mysqli_fetch_assoc($result);
echo(json_encode(array(
'Message' => "OK",
'Status' => 1,
'Surname' => $row['surname'],
'Firstname' => $row['firstname'],
'Othername' => $row['othername']
// Rest of the fields
)));
} else {
echo(json_encode(array('Message' => mysql_error($conn), 'Status' => 0)));
}
And for the client side:
ServiceResponse rr = response.body();
if (rr.getStatus().contentEquals("1"))
{
Toast.makeText(MainActivity.this, "Successfully", Toast.LENGTH_LONG).show();
txtSurname.setText(rr.getSurname());
txtFirstname.setText(rr.getFirstname());
// Rest of the fields
}
else
{
Toast.makeText(MainActivity.this,"Error", Toast.LENGTH_LONG).show();
}

Android/php: Using PDO to retrieve a set of results using 'LIKE', and parse to JSON

I'm trying to use a query to search a database, and return a few columns from a table wherever the user's name is LIKE the search query. I.e if I type in 'M', names like Max, Matthew etc. would be retrieved. However, when executed the query isn't returning anything. I've surrounded it all with try/catch functions and they work properly, echoing an integer that I can use, but I'd much prefer that the code actually did what it's meant to do. I've spent quite a while fiddling with this, first trying to use MySqli then moving to PDO since everyone online thinks it's better.
If anyone can see what's wrong with this, please don't hesitate to correct it!
The server-side script is below:
if(!empty($_POST['name'])){
$host =
$db =
$user =
$password =
$charset =
$dsn = 'mysql:host=localhost;dbname=dbname';
$opt = [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false,
];
$pdo = new PDO($dsn,$user,$password,$opt);
$response = array();
$name = $_POST['name'];
$query = "SELECT user_id, name, email FROM users WHERE name LIKE ?";
try {
$stmt = $pdo->prepare("SELECT user_id, name, email FROM users WHERE name LIKE ?");
$stmt->execute([$name]);
$result = $stmt->fetch();
} catch (Exception $e) {
echo "99"; //Statement failed
}
if ($result !== false) {
foreach($result as $row) {
echo json_encode($row['user_id']);
echo json_encode($row['name']);
echo json_encode($row['email']);
}
} else {
echo '2'; //Empty result
}
$dsn = null;
} else {
echo "3"; //No search entry
}
The relevant code from AndroidStudio is as follows:
#Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
final String name = searchInput.getText().toString();
Response.Listener<String> responseListener = new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
System.out.println(response);
System.out.println(name);
if(response != null) {
System.out.println("Statement executed");
} else if (Integer.parseInt(response) == 2) {
System.out.println("Statement executed, but result invalid");
Toast.makeText(getApplicationContext(), "No results found", Toast.LENGTH_SHORT).show();
} else if (Integer.parseInt(response) == 3) {
System.out.println("Search field empty");
Toast.makeText(getApplicationContext(), "No search entry", Toast.LENGTH_SHORT).show();
} else if (Integer.parseInt(response) == 99) {
System.out.println("Failed to execute");
Toast.makeText(getApplicationContext(), "Statement failure", Toast.LENGTH_SHORT).show();
} else {
JSONArray jsonResponse = new JSONArray(response);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
};
PopupContactRequest AddContactRequest = new PopupContactRequest(name, responseListener);
RequestQueue queue = Volley.newRequestQueue(PopupAddContact.this);
queue.add(AddContactRequest);
}
Once I can actually get some useful data passed to the app, I'd like to populate a search-suggestion type listview with it, so that the user can select the appropriate person to add. If anyone also knows how to do this, feel free to add it as a comment or message me, as I need all the help I can get with this!
Cheers,
J
You want data which match beginning of string so in like you have to append % at end
try {
$stmt = $pdo->prepare("SELECT user_id, name, email FROM users WHERE name LIKE ?");
$name = $name."%"; // add this line
$stmt->execute([$name]);
$result = $stmt->fetch();
} catch (Exception $e) {
echo "99"; //Statement failed
}
To have a functional LIKE Statement you need to be aware, that you need to add a precent sign as a wildcard in mysql.
This will get Names startig with "M"
SELECT user_id, name, email FROM users WHERE name LIKE 'M%'
This will get names ending with "M"
SELECT user_id, name, email FROM users WHERE name LIKE '%M'
This will get names that contain "M" at some place
SELECT user_id, name, email FROM users WHERE name LIKE '%M%'

deleting a row in mysql and android - relational databases

In android app the user can insert a player's name, his rating and post that data in my server. This is done by the following working code.
<?php
session_start();
require "init.php";
header('Content-type: application/json');
error_reporting(E_ALL);
ini_set("display_errors", 1);
$id_isSet = isset($_POST['player_id']);
$user_id_isSet = isset($_POST['User_Id']);
$best_player_isSet = isset($_POST['player']);
$rate_isSet = isset($_POST['rating']);
if($id_isSet && $user_id_isSet && $best_player_isSet && $rate_isSet){
$id = $_POST["player_id"];
$user_id = $_POST['User_Id'];
$best_player = $_POST['player'];
$rate = $_POST['rating'];
$sql_query = "INSERT INTO rating_players_table VALUES('$id','$best_player','$rate','$user_id');";
if(mysqli_query($con,$sql_query)){
$don = array('result' =>'success','message'=>'Προστέθηκε');
//$don = array('result' =>"success","message"=>"$id");
}
}else if(!$best_player_isSet){
$don = array('result' =>"fail","message"=>"Insert player name");
}else if(!$rate_isSet){
$don = array('result' =>"fail","message"=>"Rate player");
}
echo json_encode($don);
?>
Now I want the user to delete the players he rated. So for that I am doing the following.
<?php
include("init.php");
$delete_post = "delete from rating_players_table where
id='$_GET['player_id']'";
$run_delete = mysqli_query($con,$delete_post);
echo json_encode($don);
}
?>
Do you see what I am doing in the deleting code? I use the $_GET['player_id'] is order to delete the corresponding row. However, this code doesn't work. Any ideas on this problem? I am suspecting that the $_GET['player_id'] returns nothing, even if the rating_players_table has some rows of data.
Finally this is my android code.
public void deleteRatedPlayer() {
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.GET,
URL.DELETE_RATED_PLAYER,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d("TAG", response.toString());
try {
if (response.getString("result").equals("success")) {
Toast.makeText(getApplicationContext(), response.getString("message"), Toast.LENGTH_LONG).show();
} else if (response.getString("result").equals("fail")) {
Toast.makeText(getApplicationContext(), response.getString("message"), Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(jsonObjReq);
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event)
{
return (keyCode == KeyEvent.KEYCODE_BACK ? true :
super.onKeyDown(keyCode, event));
}
}
First of all, to fix your problem fix the deletion line:
// you cannot include $_GET['player_id'] directly in your string
// between the double quotes, you need to use concatenation in this case
$delete_post = "delete from rating_players_table where id='" . $_GET['player_id'] . "'";
Although this should solve the syntax problem, you still have another one: you don't check the input. I suggest you read about prepared statements in mysqli, about filter_input and SQL injection. Each one of the topics can be easily found with simple search.
// filter_input example usage
$player_id = filter_input(INPUT_GET, 'player_id', FILTER_SANITIZE_FULL_SPECIAL_CHARS);
$delete_post = "delete from rating_players_table where id='$player_id'";
Also, I suggest you add some kind of an authorization to limit users' ability to remove another users' entries. Currently, if a player sends a request, you delete the row directly, but what if the user sends you another one's id?

Send json object data to remote mysql database in android

I have successfully fetched data from remote database using methods posted on internet.But I'm unable to push (insert) data into the same table.
I've added a static counter just to check whether the code reaches the given url, but as expected , it fails.Below is the php file I've saved up in my remote server file manager.
<?php
$json=$_GET [ 'json']; $json=f ile_get_contents( 'php://input');
$obj=json_decode($json);
$conn=mysql_connect( "mydatabasename", "myusername", "mypassword") or die( "error connecting");
mysql_select_db( "mydatabasename",$conn)or die("database couldnot connect");
error_reporting(E_ALL);
$tid=$_POST[ 'tid'];
$name=$_POST[ 'name'];
mysql_query( "insert into mytablename(tid,name) values($tid,$name)");
?>
I took two inputs in the android layout, tid, name and trying to send to remote database.
Note : database name and other details have been hidden for security purpose.
if your looking for a clean way ..i suggest you to do something like this :
register.php
<?php
include('connect.php');
$response = array();
if (isset($_POST['Nom']) && isset($_POST['Prenom']) && isset($_POST['Email'])&& isset($_POST['Mdp'])) { //checking if the required fields are set
$Nom = $_POST['Nom'];//the family name
$Prenom = $_POST['Prenom']; //last name
$Email = $db->real_escape_string($_POST['Email']);
$Mdp = $db->real_escape_string($_POST['Mdp']); //the password
if ($res = $db->query("SELECT * FROM `patient` WHERE `Email_p`='$Email' ")) {
$row_cnt = $res->num_rows; }
if($row_cnt>0) {
$response["success"] = 0;
$response["message"] = "Email exists"; }
if ($row_cnt <1){
$result = mysqli_query($db,"INSERT INTO `patient`(`Id_p`, `Nom`, `Prenom`, `Email_p`, `Mdp`) VALUES ('','$Nom','$Prenom','$Email','$Mdp')");
if ($result ) {
$response["success"] = 1; // if account created we set success value to 1
$response["message"] = "account created";
} else {
$response["success"] = 0;
$response["message"] = "Oops Error";
}}
}else {
$response["success"] = 0;
$response["message"] = "Fields messing";
}
echo json_encode($response);
?>
in android ... yourActivity.java
class CreerNouveauCompte extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(inscription.this);
pDialog.setMessage(getString(R.string.inscriEnCours));
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
protected String doInBackground(String... args) {
String nom = edtNom.getText().toString();
String prenom = edtPrenom.getText().toString();
String email = edtEmail.getText().toString();
String mdp = edtMdp.getText().toString();
JSONObject json;
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("Nom", nom));
params.add(new BasicNameValuePair("Prenom", prenom));
params.add(new BasicNameValuePair("Email", email));
params.add(new BasicNameValuePair("Mdp", mdp));
json= jsonParser.makeHttpRequest(url_register (your url),
"POST", params);
}
try {if(json != null && !json.isNull("success")){
int success = json.getInt("success");
s2=json.getString("message");
if (success == 1) { //the acount created
Intent intent;
SharedPreferences settings = getSharedPreferences("compte", 0);
SharedPreferences.Editor editor = settings.edit();
editor.putString("nom",edtNom.getText().toString() );
editor.putString("prenom",edtPrenom.getText().toString() );
editor.putString("email",edtEmail.getText().toString());
editor.putString("mdp",edtMdp.getText().toString());
editor.apply();
intent = new Intent(inscription.this,MainActivity.class);
}
startActivity(intent);
finish();
} else {
}}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String file_url) {
pDialog.dismiss();
}
}
call it like this
new CreerNouveauCompte().execute();
the connect.php
<?php
$db = new mysqli('localhost', 'root', '', 'rechmed');
mysqli_set_charset($db,'utf8');
?>
//note i use mysqli ..in your case use mysql
Use the code below if you are trying to decode a JSONObject with this format {"tid":"myTidValue", "name":"myNameValue"}
<?php
$json=stripslashes($_GET['json']);
$obj=json_decode($json, true);
$conn=mysql_connect( "mydatabasename", "myusername", "mypassword") or die( "error connecting");
mysql_select_db( "mydatabasename",$conn)or die("database couldnot connect");
error_reporting(E_ALL);
$tid=$json['tid'];
$name=$json['name'];
mysql_query("insert into mytablename(tid,name) values('$tid','$name')");
?>
and to decode a JSONArray with this format [{"tid":"myTidValue1", "name":"myNameValue1"}, {"tid":"myTidValue2", "name":"myNameValue2"}] you can use below code
<?php
$json=stripslashes($_GET['json']);
$obj=json_decode($json, true);
$conn=mysql_connect( "mydatabasename", "myusername", "mypassword") or die( "error connecting");
mysql_select_db( "mydatabasename",$conn)or die("database couldnot connect");
error_reporting(E_ALL);
foreach ($json as $data){
$tid=$data['tid'];
$name=$data['name'];
mysql_query("insert into mytablename(tid,name) values('$tid','$name')");
}
?>
if neither works, post your codes for android

Categories