Delete from Mysql (android) - php

so yesterday it was working fine , all i did today was change the url cause my ip address changes , i dont know what's wrong with it , it says * deleted perfectly* but it actually doesn't delete a thing
here's my php script
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "restaurant";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
//$_POST["sIDCOMMANDES"]=6;
$commandesID = $_POST["sIDCOMMANDES"];
$strSQL = "DELETE FROM commandes WHERE 1 AND ID_COMMANDES = '".$commandesID."' ";
$result = $conn->query($strSQL);
if(!$result)
{
$ar["StatusID"] = "0";
$ar["Error"] = "Cannot delete data!";
}
else
{
$ar["StatusID"] = "1";
$ar["Error"] = "";
}
print(json_encode($ar));
$conn->close();
?>
I ve tested it and it s working fine , now here s my code for deleting a row from my listview
public class ImageAdapter extends BaseAdapter
{
private Context context;
public View getView(final int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
convertView = inflater.inflate(R.layout.get_all_comm_list_view, null);
}
ImageButton cmdDelete = (ImageButton) convertView.findViewById(R.id.btnDelete);
cmdDelete.setBackgroundColor(Color.TRANSPARENT);
final AlertDialog.Builder adb1 = new AlertDialog.Builder(Comm.this);
final AlertDialog.Builder adb2 = new AlertDialog.Builder(Comm.this);
cmdDelete.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
adb1.setTitle("Delete?");
adb1.setMessage("Are you sure delete [" + MyArrList.get(position).get("NOM_PLAT") +"]");
adb1.setNegativeButton("Cancel", null);
adb1.setPositiveButton("Ok", new AlertDialog.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
String url = "http://192.168.1.7/deleteData.php";
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("sIDCOMMANDES", MyArrList.get(position).get("ID_COMMANDES")));
String resultServer = getJSONUrll(url, params);
String strStatusID = "0";
String strError = "Unknown Status";
try {
JSONObject c = new JSONObject(resultServer);
strStatusID = c.getString("StatusID");
strError = c.getString("Error");
} catch (JSONException e) {
e.printStackTrace();
}
if(strStatusID.equals("0"))
{
adb2.setTitle("Error! ");
adb2.setPositiveButton("Close", null);
adb2.setMessage(strError);
adb2.show();
}
else
{
Toast.makeText(Comm.this, "Delete data successfully.", Toast.LENGTH_SHORT).show();
ShowData(); // reload data again
}
}});
adb1.show();
}
});

Related

Receive Json data POST method in PHP server from Android using Volley Library

Hello I'm send an JSON object from android using volley library. I can not receive this JSON object in PHP. I checked by echo ING my JSON data I can see the object in my 'OnResponse Method'. It would be my pleaser if anyone can help me to solve it. I'll owe you a great debt. Here is my code ->
Android Volley Code ->
private void registerUser() {
JSONObject postObject = new JSONObject();
RequestQueue queue = Volley.newRequestQueue(this);
JSONObject historyObject = new JSONObject();
String url ="http://helpinghandbd.org/app/index.php";
try {
//historyObject.put("id","1");
historyObject.put("email","1234");
historyObject.put("password","1234");
postObject.put("user",historyObject);
} catch (JSONException e) {
e.printStackTrace();
}
Log.e("LoginActivityJsonObject",""+postObject);
JsonObjectRequest objRequest = new JsonObjectRequest(Request.Method.POST, url,postObject,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.e("LoginActivity","OnResponse: "+response);
Toast.makeText(LoginActivity.this, String.valueOf(response), Toast.LENGTH_LONG).show();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("OnError", String.valueOf(error.getMessage()));
}
});
queue.add(objRequest);
}
JSON Format is ->
{ 'user':{
'email':'1234',
'password':'1234'
}
}
And Finally PHP Code is ->
<?php
$data = file_get_contents("php://input");
//echo $data; -> //{ 'user':{'email':'1234','password':'1234'}};
$decode = json_decode($data,true);
$email = $decode->user['email'];
$password = $decode->user['passowrd'];
$servername = "localhost";
$username = "helpinghandbd_app";
$password = "Demopass000";
$dbname = "helpinghandbd_app";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
//$data = file_get_contents("php://input");
//{ 'user':{'email':'1234','password':'1234'}};
$sql = "INSERT INTO users (id,email,password)
VALUES (null, '$email', '$password')";
if ($conn->query($sql) === TRUE) {
echo $data;
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
I can not receive JSON Object in PHP. Thanks in advance.
In your php code, change
$decode = json_decode($data,true);
$email = $decode->user['email'];
$password = $decode->user['passowrd'];
to
$decode = json_decode($data,true);
$email = $decode['user']['email'];
$password = $decode['user']['passowrd'];

How do i insert record when row is not exist in database within one table

I am trying to insert a new record and same time it check the record is exist or not.but the query fails to show the function please give me suggestions. when application runs it shows FAILURE ( the Data could not be inserted. Signup failed.)this message from java file.I want to display messages in application records inserted or record exist.
//java file
public class SignupActivity extends AsyncTask<String, Void, String> {
private Context context;
public SignupActivity(Context context) {
this.context = context;
}
protected void onPreExecute() {
}
#Override
protected String doInBackground(String... arg0) {
String fullName = arg0[0];
// String userName = arg0[1];
String passWord = arg0[1];
String phoneNumber = arg0[2];
String emailAddress = arg0[3];
String link;
String data;
BufferedReader bufferedReader;
String result;
try {
data = "?fullname=" + URLEncoder.encode(fullName, "UTF-8");
// data += "&username=" + URLEncoder.encode(userName, "UTF-8");
data += "&password=" + URLEncoder.encode(passWord, "UTF-8");
data += "&phonenumber=" + URLEncoder.encode(phoneNumber, "UTF-8");
data += "&emailaddress=" + URLEncoder.encode(emailAddress, "UTF-8");
link = "http://mydoamin.com/mangoair10/tryrr.php" + data;
URL url = new URL(link);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
bufferedReader = new BufferedReader(new InputStreamReader(con.getInputStream()));
result = bufferedReader.readLine();
return result;
} catch (Exception e) {
return new String("Exception: " + e.getMessage());
}
}
#Override
protected void onPostExecute(String result) {
String jsonStr = result;
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
String query_result = jsonObj.getString("query_result");
if (query_result.equals("SUCCESS")) {
Toast.makeText(context, "Data inserted successfully. Signup successfull.", Toast.LENGTH_LONG).show();
} else if (query_result.equals("FAILURE")) {
Toast.makeText(context, "Data could not be inserted. Signup failed.", Toast.LENGTH_SHORT).show();
}
else {
Toast.makeText(context, "Couldn't connect to remote database.", Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
// Toast.makeText(context, "Error parsing JSON Please data Fill all the records.", Toast.LENGTH_SHORT).show();
Toast.makeText(context, "Please LogIn", Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(context, "Couldn't get any JSON data.", Toast.LENGTH_SHORT).show();
}
}
}
//php file
<?php
$con=mysqli_connect("localhost","user","password","database");
if (mysqli_connect_errno($con))
{
echo '{"query_result":"ERROR"}';
}
$fullName = $_GET['fullname'];
//$userName = $_GET['username'];
$passWord = $_GET['password'];
$phoneNumber = $_GET['phonenumber'];
$emailAddress = $_GET['emailaddress'];
$sql = "INSERT INTO users10 (fullname,password,phone,email)
SELECT * FROM (SELECT '$fullName', '$passWord', '$phoneNumber','$emailAddress') AS tmp
WHERE NOT EXISTS (
SELECT name FROM users10 WHERE phone = '$phoneNumber' OR email='$emailAddress'
) LIMIT 1 ";
$result=mysqli_query($con,$sql);
if($result == true)
{
echo '{"query_result":"SUCCESS"}';
}else{
echo '{"query_result":"FAILURE"}';
}
mysqli_close($con);
?>
As #ali already said you need to check for user existence an then go ahead and create it:
/* Connect to the DB using MySQLi class */
$mysql = new mysqli('localhost', 'user', 'password', 'database');
/* If an error code is reported... */
if($mysql->connect_errno)
{
echo json_encode(array(
'query_result' => 'ERROR'
));
}
/* Otherwise go ahead... */
else
{
/* Prepare a select statement to check user existence */
$selectStmt = $mysql->prepare("SELECT * FROM `users10` WHERE `phone` = ? OR `email` = ?");
/* Retrieve arguments */
$fullName = $_GET['fullname'];
//$userName = $_GET['username'];
$passWord = $_GET['password'];
$phoneNumber = $_GET['phonenumber'];
$emailAddress = $_GET['emailaddress'];
/* Binding parameters */
$selectStmt->bind_param('ss', $phoneNumber, $emailAddress);
/* Execute statement */
if (!$selectStmt->execute()) {
echo json_encode(array(
'query_result' => 'ERROR'
));
}
else
{
/* If the number of returned rows is 0 */
if(0 === $selectStmt->get_result()->num_rows)
{
$insertStmt = $mysql->prepare("INSERT INTO `users10` (`fullname`, `password`, `phone`, `email`) VALUES (?, ?, ?, ?)");
$insertStmt->bind_param('ssss', $fullName, $passWord, $phoneNumber, $emailAddress);
/* Try to insert the new user */
if (!$insertStmt->execute()) {
echo json_encode(array(
'query_result' => 'FAILURE'
));
}
else
{
echo json_encode(array(
'query_result' => 'SUCCESS'
));
}
}
else
{
echo json_encode(array(
'query_result' => 'FAILURE'
));
}
}
}
I think you need ' ON DUPLICATE KEY UPDATE '
this will update a given record when it is present, but insert a new one if not.
on duplicate key

Android force close after sending data to server via php

I have a program to read data from SQL Server using php file. When I running my program and click the button search my program always close. In my logcat no one error message
My code android like this
Toolbar toolbar;
// Progress Dialog
private ProgressDialog pDialog;
JSONParser jsonParser = new JSONParser();
EditText inputign;
TextView registerErrorMsg;
Button searchign;
// url to create news
private static String url_create_idgm = "http://192.168.1.111/add/csp_ign.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_cps_ign);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
TypedValue typedValueColorPrimaryDark = new TypedValue();
CSPviaIGN.this.getTheme().resolveAttribute(R.attr.colorPrimary, typedValueColorPrimaryDark, true);
final int colorPrimaryDark = typedValueColorPrimaryDark.data;
if (Build.VERSION.SDK_INT >= 21) {
getWindow().setStatusBarColor(colorPrimaryDark);
}
// Edit Text
inputign = (EditText) findViewById(R.id.inputign);
registerErrorMsg = (TextView) findViewById(R.id.error);
// Create button
searchign = (Button) findViewById(R.id.btnign);
// button click event
searchign.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// creating new product in background thread
new NetCheck().execute();
}
});
}
/**
* Background Async Task to Create new product
* */
class NetCheck extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(CSPviaIGN.this);
pDialog.setMessage("Creating ID Game Master..");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
/**
* Creating product
* */
protected String doInBackground(String... args) {
String name = inputign.getText().toString();
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("ign", name));
// getting JSON Object
// Note that create product url accepts POST method
JSONObject obj = jsonParser.makeHttpRequest(url_create_idgm,
"POST", params);
// check log cat fro response
Log.d("Create Response", obj.toString());
// check for success tag
try {
int success = obj.getInt(TAG_SUCCESS);
if (success == 1) {
// successfully created product
//Toast.makeText(CreateIDGM.this, "Success Create ID Game Master ", Toast.LENGTH_SHORT).show();
//JSONObject obj = jParser.makeHttpRequest(url_create_idgm, "GET", params);
JSONArray account = obj.getJSONArray("detail");
JSONObject firstOnlineObject = account.getJSONObject(0);
String accountign = firstOnlineObject.getString("Account");
JSONArray ign = obj.getJSONArray("detail");
JSONObject secondOnlineObject = ign.getJSONObject(0);
String Name = secondOnlineObject.getString("Name");
JSONArray race = obj.getJSONArray("detail");
JSONObject thirdOnlineObject = race.getJSONObject(0);
String bangsa = thirdOnlineObject.getString("Race");
JSONArray classign = obj.getJSONArray("detail");
JSONObject forthOnlineObject = classign.getJSONObject(0);
String job = forthOnlineObject.getString("Class");
JSONArray map = obj.getJSONArray("detail");
JSONObject fifthOnlineObject = map.getJSONObject(0);
String location = fifthOnlineObject.getString("Map");
JSONArray level = obj.getJSONArray("detail");
JSONObject sixthOnlineObject = level.getJSONObject(0);
String Lv = sixthOnlineObject.getString("Level");
JSONArray dalant = obj.getJSONArray("detail");
JSONObject seventhOnlineObject = dalant.getJSONObject(0);
String money = seventhOnlineObject.getString("Dalant");
JSONArray gold = obj.getJSONArray("detail");
JSONObject eighthOnlineObject = gold.getJSONObject(0);
String emas = eighthOnlineObject.getString("Gold");
JSONArray pvp = obj.getJSONArray("detail");
JSONObject ninthOnlineObject = pvp.getJSONObject(0);
String pvppoint = ninthOnlineObject.getString("PVP Point");
JSONArray cpt = obj.getJSONArray("detail");
JSONObject tenOnlineObject = cpt.getJSONObject(0);
String cptpoint = tenOnlineObject.getString("CPT Point");
JSONArray cc = obj.getJSONArray("detail");
JSONObject ccOnlineObject = cc.getJSONObject(0);
String cashcoin = ccOnlineObject.getString("Cash Coin");
JSONArray ps = obj.getJSONArray("detail");
JSONObject psOnlineObject = ps.getJSONObject(0);
String premi = psOnlineObject.getString("Premium Service");
// TextView data
TextView id = (TextView)findViewById(R.id.accountplayer);
id.setText(accountign); // id
TextView ignname = (TextView)findViewById(R.id.ignPlayer);
ignname.setText(Name); // ign
TextView raceign = (TextView)findViewById(R.id.serialplayer);
raceign.setText(bangsa); // race
TextView jobign = (TextView)findViewById(R.id.raceplayer);
jobign.setText(job); // job
TextView mapign = (TextView)findViewById(R.id.classplayer);
mapign.setText(location); // map
TextView lvign = (TextView)findViewById(R.id.lvlplayer);
lvign.setText(Lv); //level
TextView dalantign = (TextView)findViewById(R.id.dalantplayer);
dalantign.setText(money); // dalant
TextView goldign = (TextView)findViewById(R.id.goldplayer);
goldign.setText(emas); // gold
TextView pvpign = (TextView)findViewById(R.id.pvpplayer);
pvpign.setText(pvppoint); // pvp
TextView cptign = (TextView)findViewById(R.id.cptplayer);
cptign.setText(cptpoint); //cpt
TextView cashign = (TextView)findViewById(R.id.cc);
cashign.setText(cashcoin); // cash
TextView premiign = (TextView)findViewById(R.id.premi);
premiign.setText(premi); // premi
// closing this screen
finish();
} else {
// failed to create product
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String file_url) {
// dismiss the dialog once done
pDialog.dismiss();
Intent i = new Intent(getApplicationContext(), CSPviaIGN.class);
//i.putExtra("key",inputign.getText().toString());
startActivity(i);
}
}
My code php like this
<?php
//$_POST['ign'] = "CaptainJugger";
// array for JSON response
$response = array();
// check for required fields
if (isset($_POST['ign'])) {
$ign = $_POST['ign'];
/* All database connection variables */
define('DB_USER', ""); // db user
define('DB_PASSWORD', ""); // db password
define('DB_DATABASE', "RF_World"); // database name
define('DB_SERVER', "127.0.0.1"); // db server
class DB_CONNECT {
// constructor
function __construct() {
// connecting to database
$this->connect();
}
// destructor
function __destruct() {
// closing db connection
$this->close();
}
/** Function to connect with database **/
function connect() {
// Connecting to mssql database
$con = mssql_connect(DB_SERVER, DB_USER, DB_PASSWORD) or die(mssql_error());
// Selecing database
$db = mssql_select_db(DB_DATABASE) or die(mssql_error()) or die(mssql_error());
// returing connection cursor
return $con;
}
/** Function to close db connection **/
function close() {
// closing db connection
mssql_close();
}
}
// connecting to db
$db = new DB_CONNECT();
// mssql inserting a new row
$result = mssql_query("SELECT Account, Name, Race, Class, Map, Lv, Dalant, Gold, c.PvpPoint, PvpCash, Cash, d.Status FROM tbl_base a
INNER JOIN tbl_general b ON b.Serial = a.Serial
INNER JOIN tbl_pvporderview c ON c.serial = a.Serial
INNER JOIN [BILLING].[dbo].tbl_UserStatus d ON d.id = a.Account
WHERE Name= '$ign';");
// status premium service
if ($res['Status'] == 1){
$status = 'Deactive';
} else {
$status = 'Active';
}
// status race
if ($res['Race'] == 0){
$race = 'Bellato';
} elseif ($res['Race'] == 1){
$race = 'Bellato';
} elseif ($res['Race'] == 2){
$race = 'Cora';
} elseif ($res['Race'] == 3){
$race = 'Cora';
} else {
$race = 'Accretia';
}
// check if row inserted or not
if (mssql_num_rows($result) > 0) {
// looping through all results
// products node
$response["detail"] = array();
while ($row = mssql_fetch_array($result)) {
// temp user array
$product = array();
$product["Account"] = $row["Account"];
$product["Name"] = $row["Name"];
$product["Race"] = $row["Race"];
$product["Class"] = $row["Class"];
$product["Map"] = $row["Map"];
$product["Level"] = $row["Lv"];
$product["Dalant"] = $row["Dalant"];
$product["Gold"] = $row["Gold"];
$product["PVP Point"] = $row["PvpCash"];
$product["CPT Point"] = $row["PvpPoint"];
$product["Cash Coin"] = $row["Cash"];
$product["Premium Service"] = $row["Status"];
// push single product into final response array
array_push($response["detail"], $product);
}
// success
$response["success"] = 1;
// echoing JSON response
echo json_encode($response);
} else {
// no products found
$response["success"] = 0;
$response["message"] = "No News DZoneConnect Now";
}
}
else {
// required field is missing
$response["success"] = 0;
$response["message"] = "Required field(s) is missing";
// echoing JSON response
echo json_encode($response);
}
?>
My code php when I run in browser like this http://prntscr.com/bfjl5a and http://prntscr.com/bfjlf3
Anyone can help me to solve my problem?

Send Json String using volley to php and decode it

I know how to send data using volley library and get those from php. Problem is, I want to send a Json String and decode those data from the php side.
This is the method I am using to send data using param. Last item is the json String
private void checkOrderNo() {
pDialog.setMessage("Sending...");
showDialog();
DateFormat df = new SimpleDateFormat("yyyy/MM/dd hh:mm:ss");
final String nowDate = df.format(new Date());
//final day of the month
Date today = new Date();
Calendar calendar = Calendar.getInstance();
calendar.setTime(today);
calendar.add(Calendar.MONTH, 1);
calendar.set(Calendar.DAY_OF_MONTH, 1);
calendar.add(Calendar.DATE, -1);
Date lastDayOfMonth = calendar.getTime();
DateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
final String lastDate = sdf.format(lastDayOfMonth);
Log.d("Last day ", sdf.format(lastDayOfMonth) + " // Today" + nowDate);
// Tag used to cancel the insert
String tag_string_req = "req_insert";
final StringRequest strReq = new StringRequest(Request.Method.POST,
AppConfig.URL_ITEM_DETAILS_SEND, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
hideDialog();
try {
JSONObject jObj = new JSONObject(response);
if (jObj.names().get(0).equals("found")) {
newOrderId = jObj.getString("found").toString();
orderIdForItemTable = newOrderId;
Log.d(TAG, "newOrderId: " + newOrderId);
Log.d(TAG, "New repID 2 inserted into sqlite: " + newOrderId + " " + nowDate);
sqLiteHandler.addItemDetails(newOrderId, repID, dealerID, nowDate, lastDate, selectedDisChannel);
finish();
Bundle basket = new Bundle();
basket.putString("dealerName", dealerName);
basket.putString("orderNo", newOrderId);
basket.putString("jsonString", json_string);
Intent intent = new Intent(SelectItem.this, ItemCart.class);
intent.putExtras(basket);
startActivity(intent);
finish();
} else {
Toast.makeText(getApplicationContext(), "Invalied Request", Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Inserting Error: " + error.getMessage());
Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_LONG).show();
}
}) {
#Override
protected Map<String, String> getParams() {
// Posting params to register url
Map<String, String> params = new HashMap<String, String>();
params.put("order_no", orderId);
params.put("repID", repID);
params.put("dealerID", dealerID);
params.put("nowDate", nowDate);
params.put("lastDate", lastDate);
params.put("disChannel", selectedDisChannel);
params.put("jsonString", json_string);
return params;
}
};
strReq.setRetryPolicy(new DefaultRetryPolicy(15000, 1,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
// Adding request to request queue
AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
}
This is my PhP for volley
<?php
require_once 'include/Config_test.php';
$con = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD) or die("connection failed");
mysql_select_db(DB_DATABASE,$con) or die("db selection failed");
$order_no = $repID = $dealerID = $nowDate = $jsonString = $lastDate = $disChannel = "";
if(isset($_POST['order_no'])){
$order_no = $_POST['order_no'];
$repID = $_POST['repID'];
$dealerID = $_POST['dealerID'];
$nowDate = $_POST['nowDate'];
$lastDate = $_POST['lastDate'];
$disChannel = $_POST['disChannel'];
$jsonString= $_POST['jsonString'];
}
$result = mysql_query("SELECT MAX(order_no) FROM tbl_items_header_t");
$row = mysql_fetch_row($result);
if($row[0] < 70000000){
$highest_id = 70000000;
} else{
$highest_id = $row[0] + '1';
}
//$highest_id = $row[0] + '1';
$query = mysql_query("INSERT INTO tbl_items_header_t(order_no,rep_no,dealer_no,order_date,last_date,dis_channel,status)
VALUES('$highest_id','$repID','$dealerID','$nowDate','$lastDate','$disChannel','')");
$json['found']= $highest_id;
echo json_encode($json);
?>
I know send json String using DefaultHttpClient but it is deprecated. I have to use two PHP also. I want to do it using volley.
This is what I use for get json String using DefaultHttpClient. It worked. But I want to use this in the volley.
<?php
require_once 'include/Config_test.php';
$con = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD) or die("connection failed");
mysql_select_db(DB_DATABASE,$con) or die("db selection failed");
$postdata = file_get_contents('php://input');
$data = json_decode($postdata, true);
if (is_array($data['sending_items'])) {
foreach ($data['sending_items'] as $record) {
$order_no = $record['order_no'];
$items = $record['items'];
$items_no = $record['items_no'];
$plant = $record['plant'];
$quantity = $record['quantity'];
mysql_query("INSERT INTO tbl_item_list(order_no, items, items_no, plant, quantity) VALUES('$order_no', '$items', '$items_no', '$plant', '$quantity')");
}
}
echo json_encode($data);
mysql_close($con);
?>

Posting JSON file on a PHP file from Android Application, and decoding JSON to local variables on PHP

I have been researching this for a while now and not getting anywhere.
What I'm trying to do is to create a registrion/login activities, which will store all access details on a remote SQL database.
My outline of the code was to create the "Registrar" object, convert it to JSON object, and convert that JSON object to a string, and then send that string over httpclient as a post to the PHP page ( which is located on my XAMPP ), kindly take note that I'm using Android Studio Emulator.
My problem:
I don't know if the JSON file is received by the PHP server or not.
Here is my code:
Submit function:
public void goSubmit(View view) throws IOException {
EditText nameEdit = (EditText) findViewById(R.id.nameEdit);
EditText idEdit = (EditText) findViewById(R.id.idEdit);
String name = nameEdit.getText().toString();
String ID = idEdit.getText().toString();
//Creating Student (Registrar) Object
Student registrar = new Student();
registrar.setMajor(majorEdit);
registrar.setName(name);
registrar.setId(ID);
//Creating JSON String
String registrarJSON = null;
try {
registrarJSON = ObjInJSON(registrar);
Toast.makeText(this, registrarJSON, Toast.LENGTH_LONG).show();
} catch (JSONException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
//Posting JSON String on Remote PHP
String PHPresponse = sendToRegistrationPHP(registrarJSON);
Toast.makeText(this, PHPresponse, Toast.LENGTH_LONG).show();
//Receive PIN from PHP as JSON String
//Parsing JSON string to integer (pin)
//Set PIN in registrar.getpin()
//Passing the object to setPassword Activity condition registrar.pin =! null
}
Student class:
public class Student {
String Id = "NULL" ;
String Major = "NULL";
String Name = "NULL";
String Password = "NULL";
String Pin = "NULL";
public String getPin() {
return Pin;
}
public void setPin(String pin) {
Pin = pin;
}
public String getPassword() {
return Password;
}
public void setPassword(String password) {
Password = password;
}
public String getId() {
return Id;
}
public String setId(String id) {
Id = id;
return id;
}
public String getName() {
return Name;
}
public void setName(String name) {
Name = name;
}
public String getMajor() {
return Major;
}
public void setMajor(String major) {
Major = major;
}
}
Creating JSON object in string format:
protected String ObjInJSON(Student studentC) throws JSONException, UnsupportedEncodingException {
String ID = studentC.getId();
String Pin = studentC.getPin();
String Major = studentC.getMajor();
String Password = studentC.getPassword();
String Name = studentC.getName();
JSONObject json_obj = new JSONObject();
json_obj.put("id", ID);
json_obj.put("password", Password);
json_obj.put("pin", Pin);
json_obj.put("major", Major);
json_obj.put("name", Name);
return json_obj.toString();
}
Sending to PHP server:
public static String sendToRegistrationPHP(String jarr) throws IOException {
StringBuffer response = null;
try {
String myurl = "10.0.2.2:8070/StudentaccistancePHP/MySqlTEST.php";
URL url = new URL(myurl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(10000);
conn.setConnectTimeout(15000 /* milliseconds */);
conn.setRequestProperty("Content-Type", "application/json");
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setRequestMethod("POST");
OutputStream out = new BufferedOutputStream(conn.getOutputStream());
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(out, "UTF-8"));
writer.write(jarr);
writer.close();
out.close();
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String inputLine;
response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
System.out.println("Response in universal: " + response.toString());
} catch (Exception exception) {
System.out.println("Exception: " + exception);
}
if (response != null) {
return response.toString();
}
else return "Not WORKING !";
}
PHP server:
<?php
$json = file_get_contents('php://input');
$data = json_decode($json, true);
$ID = $data['id'];
$password = $data['password'];
$pin = "323232";
$major = $data['major'];
$name = $data['name'];
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "studentassictance";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully";
$sql = "INSERT INTO students (id, major, name, password, pin)
VALUES ('$ID', '$major', '$name', '$password', '$pin')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully <br>";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
?>
However, nothing is inserted to the database.
First, you need to check what arrives as JSON into PHP side. You can
var_dump($json,$data);
after json_encode() call and watch it to be a valid JSON. You can validate it here
Second, show you SHOW CREATE TABLE students
And third, rewrite everything to PDO as it supports named parameters and it would be theoretically easier for you to migrate to another DB engine later if needed. So it would be something like:
<?php
define('DSN','mysql:dbname=test;host=localhost');
define('DB_USERNAME','testuser');
define('DB_PASSWORD','testpassword');
$connect = new PDO(DSN, DB_USERNAME, DB_PASSWORD);
$json = file_get_contents('php://input');
/*$json = '{
"id": "111",
"password": "sfsdfsdf",
"major": "Math",
"name": "Test User"
}';*/
$data = json_decode($json, true);
$ID = $data['id'];
$password = $data['password'];
$pin = "323232";
$major = $data['major'];
$name = $data['name'];
$sql = "INSERT INTO `students`(`id`,`major`, `name`, `password`, `pin`) VALUES(:id, :major, :name, :password, :pin)";
$result = $connect->prepare($sql);
//bind parameter(s) to variable(s)
$result->bindParam( ':id', $ID, PDO::PARAM_INT );
$result->bindParam( ':major', $major, PDO::PARAM_STR );
$result->bindParam( ':name', $name, PDO::PARAM_STR );
$result->bindParam( ':password', $password, PDO::PARAM_STR );
$result->bindParam( ':pin', $pin, PDO::PARAM_STR );
$status = $result->execute();
if ($status)
{
echo "New record created successfully <br>";
} else
{
echo "Error: <br>" .
var_dump($connect->errorInfo(),$status);
}
$connect = null;

Categories