I'll just keep this question short. What is wrong with my php code, it keeps outputting 0 or Required Field(s) is missing. Here's the code
<?php
// array for JSON response
$response = array();
// check for required fields
if (isset($_POST['id']) && isset($_POST['status_id'])) {
$id = $_POST['id'];
$status_id = $_POST['status_id'];
// include db connect class
require_once __DIR__ . '/db_connect.php';
// connecting to db
$db = new DB_CONNECT();
// mysql update row with matched pid
$result = mysql_query("UPDATE pims_liip_pallet_purchase_order SET status = '$status_id' WHERE id = $id");
// check if row inserted or not
if ($result) {
// successfully updated
$response["success"] = 1;
$response["message"] = "Product successfully updated.";
// echoing JSON response
echo json_encode($response);
} else {
}
} else {
// required field is missing
$response["success"] = 0;
$response["message"] = "Required field(s) is missing";
// echoing JSON response
echo json_encode($response);
}
?>
Here is the post data in my app
protected String doInBackground(String... args) {
// TODO Auto-generated method stub
// Check for success tag
int success;
String status_id = statusID.getText().toString();
try {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("status_id", status_id));
Log.d("request!", "starting");
//Posting user data to script
JSONObject json = jsonParser.makeHttpRequest(
UPDATE_COMMENTS_URL, "POST", params);
// full json response
Log.d("Post Update", json.toString());
// json success element
success = json.getInt(TAG_SUCCESS);
if (success == 1) {
Log.d("Updated!", json.toString());
finish();
return json.getString(TAG_MESSAGE);
}else{
Log.d("Update Failure!", json.getString(TAG_MESSAGE));
return json.getString(TAG_MESSAGE);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
Any answers will be very much honored :D Thanks!
Your error says it all. Since you get to the } else { ... } bit, it means isset($_POST['id']) && isset($_POST['status_id']) is false.
In other words, your form is either:
not using POST, but GET. In that case add method="post" to your <form> tag. (actually, POST is default behaviour, so if this is the case, you probably have to remove or change method="GET" from the form tag)
and/or your form does not contain input fields with name="id" and/or name="status_id"
The updated question adds Android code. Hence this update:
I doubt that jsonParser.makeHttpRequest actually posts a form encoded json string. It more then likely will just POST json data to the webserver. PHP's $_POST will not automatically be filled with this data, since it only handles form encoded data.
You probably need to read this data from stdIn.
Try:
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$rawPostData = file_get_contents("php://input");
$postData = (array)json_decode($rawPostData);
}
And then use $postData where you otherwise would use $_POST
Just debug the $_POST['id'] and $_POST['status_id'].
Before this line.
if (isset($_POST['id']) && isset($_POST['status_id'])) {
you will find answer automatically. Hopefully one of two post variables is not set.
For debug use print_r($_POST);
Related
I am trying to send json object in android to local php server(XAMPP).
Here is my php script which recieves that object.
<?php
$response = array();
if (isset(($_POST['PNR_NO'])&&($_POST['Status'])&&($_POST['update_time']))){
$PNR_NO = $_POST['PNR_NO'];
$Status = $_POST['Status'];
$update_time = $_POST['update_time'];
// 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 pnr_database(PNR_NO, Status,update_time) VALUES('$PNR_NO', '$Status', '$update_time')");
// check if row inserted or not
if ($result) {
// successfully inserted into database
$response["success"] = 1;
$response["message"] = "Product successfully created.";
// 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 {
$response["success"] = 0;
$response["message"] = "Required field(s) is missing";
echo json_encode($response);
}?>
And the java code that i am using is :
#Override
protected Void doInBackground(String... urls) {
OutputStream os;
HttpURLConnection conn = null;
try {
//constants
String pnr = "1234";
String stat = "WC12";
String updTime = "13:20";
Log.i("aaaaa", "Started");
URL url = new URL(urls[0]);
JSONObject jsonObject = new JSONObject();
jsonObject.put("PNR_NO",pnr );
jsonObject.put("Status", stat);
jsonObject.put("update_time", updTime);
String message = jsonObject.toString();
System.out.println(message);
conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(10000 /*milliseconds*/);
conn.setConnectTimeout(15000 /* milliseconds */);
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setFixedLengthStreamingMode(message.getBytes().length);
conn.setRequestProperty("Content-Type", "application/json;charset=utf-8");
conn.setRequestProperty("X-Requested-With", "XMLHttpRequest");
//open
conn.connect();
//setup send
os = new BufferedOutputStream(conn.getOutputStream());
os.write(message.getBytes());
Log.i("aaaaa","ended");
//clean up
os.flush();
}
catch (IOException e) {
e.printStackTrace();
}
catch (JSONException ex) {
ex.printStackTrace();
}
finally {
//clean up
/*try {
os.close();
is.close();
}
catch (IOException e) {
e.printStackTrace();
}
*/
conn.disconnect();
}
return null;
}
Basically I want to send data to my php server where I have created a database which has a table named pnr_database and the sent data should get stored in that table.I don't want any response from server.
But my code is not working...
I tested my php script from a html form where i was sending data to server... In that case php script was working fine and data was getting stored in database But i am not able to make it work in android.
This might be a little late answer. But the JSON you receive in php is encoded so you need to decode it as such in your if clause:
$decoded = json_decode($_POST, true); //this will return an array
$PNR_NO = $decoded['PNR_NO'];
$Status = $decoded['Status'];
$update_time = $decoded['update_time'];
Here you can enter the columns to your table.
I made a post request with the following code in Android using Volley.
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Method.POST, ServerURL.URL_REGISTER, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d(TAG_REGISTER, "Register Response: " + response.toString());
pDialog.dismiss();
try {
JSONObject jObj = new JSONObject(response.toString());
boolean error = jObj.getBoolean("error");
if (!error) {
// User successfully stored in MySQL
// Now store the user in sqlite
String uid = jObj.getString("uid");
JSONObject user = jObj.getJSONObject("user");
String name = user.getString("name");
String email = user.getString("email");
String created_at = user
.getString("created_at");
// Inserting row in users table
db.addUserIntoSQLite(name, email, uid, created_at);
Toast.makeText(getActivity(), "User successfully registered. Try login now!", Toast.LENGTH_LONG).show();
// Launch main activity
Intent intent = new Intent(getActivity(), MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
getActivity().overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
startActivity(intent);
getActivity().finish();
} else {
// Error occurred in registration. Get the error
// message
String errorMsg = jObj.getString("error_msg");
Toast.makeText(getActivity(), errorMsg, Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
Toast.makeText(getActivity(), "JSONException: " + e.getMessage(), Toast.LENGTH_LONG).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG_REGISTER, "Registration Error: " + error.getMessage());
Toast.makeText(getActivity(), error.getMessage(), Toast.LENGTH_LONG).show();
pDialog.dismiss();
}
}) {
#Override
public String getBodyContentType() {
return "application/json; charset=utf-8";
}
#Override
protected Map<String, String> getParams() throws AuthFailureError {
HashMap<String, String> params = new HashMap<>();
params.put("tag", "register");
params.put("name", name);
params.put("email", email);
params.put("password", password);
return params;
}
};
Now here's the PHP part that receives the post request and get the post values.
<?php
session_start();
if (!empty($_POST['tag'])) {
// get tag
$tag = $_POST['tag'];
// include db handler
require_once 'mysql/DB_Functions.php';
$db = new DB_Functions();
// response Array
$response = array("tag" => $tag, "error" => FALSE);
// check for tag type
if ($tag == 'login') {
// Request type is check Login
$email = $_POST['email'];
$password = $_POST['password'];
// check for user
$user = $db->getUserByEmailAndPassword($email, $password);
if ($user != false) {
// user found
$response["error"] = FALSE;
$response["uid"] = $user["unique_id"];
$response["user"]["name"] = $user["name"];
$response["user"]["email"] = $user["email"];
$response["user"]["created_at"] = $user["created_at"];
$response["user"]["updated_at"] = $user["updated_at"];
echo json_encode($response);
} else {
// user not found
// echo json with error = 1
$response["error"] = TRUE;
$response["error_msg"] = "Incorrect email or password!";
echo json_encode($response);
}
} else if ($tag == 'register') {
// Request type is Register new user
$name = $_POST['name'];
$email = $_POST['email'];
$password = $_POST['password'];
// check if user is already existed
if ($db->userExists($email)) {
// user is already existed - error response
$response["error"] = TRUE;
$response["error_msg"] = "User already exists";
echo json_encode($response);
} else {
// store user
$user = $db->storeUser($name, $email, $password);
if ($user) {
// user stored successfully
$response["error"] = FALSE;
$response["uid"] = $user["unique_id"];
$response["user"]["name"] = $user["name"];
$response["user"]["email"] = $user["email"];
$response["user"]["created_at"] = $user["created_at"];
$response["user"]["updated_at"] = $user["updated_at"];
echo json_encode($response);
} else {
// user failed to store
$response["error"] = TRUE;
$response["error_msg"] = "Error occured in Registartion";
echo json_encode($response);
}
}
} else {
// user failed to store
$response["error"] = TRUE;
$response["error_msg"] = "Unknow 'tag' value. It should be either 'login' or 'register'";
echo json_encode($response);
}
} else {
$response["error"] = TRUE;
$response["error_msg"] = "Operation failed due to the missing tag!";
echo json_encode($response);
}
var_dump($_SERVER['REQUEST_METHOD'], $_POST);
?>
I should be able to get the 'tag' value, but the problem is that it keeps saying that the 'tag' is missing.
So now I created an HTML file to test which part has a problem.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<form action="index.php" method="post">
Tag: <input type="text" name="tag"><br>
Name: <input type="text" name="name"><br>
Email: <input type="text" name="email"><br>
Password: <input type="password" name="password"><br>
<input type="submit">
</form>
</body>
</html>
As I put the data in this HTML file, the data is successfully stored in the MySQL database. Which part do you think has the problem?
I've searched all the solutions regarding the Volley part, and my Volley part doesn't seem to have the problem. So I believe it's the PHP part that's causing the issue.
If I open the PHP file on the web, it shows the following message.
{"error":true,"error_msg":"Operation failed due to the missing tag!"}string(3) "GET" array(0) { }
The problem is that you are sending data from the Volley library as content type application/json but your PHP script is expecting POST data as content type application/x-www-form-urlencoded. This is why your POST from the web form worked, but your POST from Volley did not.
In your PHP script, do this:
$data = json_decode(file_get_contents('php://input'), true);
if (empty($data['tag']) == false) {
$tag = $data['tag'];
echo $tag;
}
Because you're sending the data as JSON, PHP won't automatically parse it into the $_POST global. What the code above does is get the raw POST data as a string and parse it into an array.
Update
I spent some more time debugging this and now have a full solution:
PHP:
Change your script to access the raw POST data using the method I listed above, instead of $_POST global. Use this code for debugging purposes:
<?php
$data = json_decode(file_get_contents('php://input'), true);
if (empty($data['tag']) == false) {
$tag = $data['tag'];
}
echo json_encode([ "tag" => $tag ]);
?>
Android:
getParams() is apparently not used with JsonObjectRequest class, so your body is empty. See the answer to this question for details of that. Instead, you must pass your body as a JsonObject in the constructor to JsonObjectRequest. For example:
HashMap<String, String> params = new HashMap<>();
params.put("tag", "register");
params.put("name", "myname");
params.put("email", "myname#email.com");
params.put("password", "meow");
JSONObject o = new JSONObject(params);
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(
Request.Method.POST,
ServerURL.URL_REGISTER,
o,
new Response.Listener<JSONObject>() { // ...
Result:
D/EXAMPLE: Register Response: {"tag":"register"}
I've created a more complete example as a gist.
Note: If you are making requests to a development server on your local machine, you'll need to use 10.0.2.2:PORT instead of localhost:PORT. I'm assuming that this is not an issue in your case, since you seem able to connect to your server, but include this note for completeness for any future readers.
I have code that I'm trying to submit to a database, and the code works fine on an emulator but as soon as I move to an actual device the same code will no longer work. I think it has to do with the time() function in my php (I don't know what else it could be) but am I missing something obvious? this code on a physcial android device always throws "Oops! An error occurred." but on my emulator on my computer it works just fine. I've checked to make sure that I uploaded fresh copies of the project.
<?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['assemblyLotNumber']) && isset($_POST['assemblyID']) && isset($_POST['assemblerID']) && isset($_POST['quantity'])) {
$assemblyLotNumber = $_POST['assemblyLotNumber'];
$assemblyID = $_POST['assemblyID'];
$assemblerID = $_POST['assemblerID'];
$quantity = $_POST['quantity'];
// include db connect class
require_once __DIR__ . '/db_connect.php';
$time = time();
// connecting to db
$db = new DB_CONNECT();
// mysql inserting a new row
$result = mysql_query("INSERT INTO assemblylot (assemblyLotNumber, assemblyID, assemblerID, date, isPremade, quantity) VALUES('$assemblyLotNumber', '$assemblyID', '$assemblerID', $time, 1, '$quantity')");
// check if row inserted or not
if ($result) {
// successfully inserted into database
$response["success"] = 1;
$response["message"] = "premade assembly successfully created.";
$response["date"] = $time;
// echoing JSON response
echo json_encode($response);
} else {
// failed to insert row
$response["success"] = 0;
$response["message"] = "Oops! An error occurred.";
$response["date"] = $time;
// 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);
}
?>
this is where I call it in the code
public void submitAssemblyLot(Assembly a) {
List<NameValuePair> assemblyParam = new ArrayList<NameValuePair>();
assemblyParam.add(new BasicNameValuePair("assemblyLotNumber", Integer.toString(a.getAssemblyLotNumber())));
assemblyParam.add(new BasicNameValuePair("assemblyID", Integer.toString(a.getAssemblyID())));
assemblyParam.add(new BasicNameValuePair("assemblerID", Integer.toString(a.getAssemblerID())));
try {
JSONObject json = jsonParser.makeHttpRequest(
url_submit_assembly_lot, "POST", assemblyParam);
String message = json.getString("message");
String date1 = json.getString("time");
Log.d("submitAssemblyLot", message);
Log.d("submitAssemblyLot", date1);
} catch (JSONException e) {
e.printStackTrace();
}
}
I am trying to get a single field from MySQL through php and use it in my android app.. how can i get a single field when reading response from php to android without using json?
or if there is any tutorial that can help me , I'll be grateful
here's my Code
public Boolean postData(String a,String b) {
response = null;
String response = null;
try
{
// url = new URL("http://"+"URL"+"/new/check2.php");
ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("check",x));
postParameters.add(new BasicNameValuePair("username", a));
postParameters.add(new BasicNameValuePair("password", b));
response = CustomHttpClient.executeHttpPost("http://"+"URL"+"/new/checkedited.php",postParameters);
// result = response.toString();
result = result.replaceAll("\\s+", "");
}
catch(Exception e)
{
e.printStackTrace();
}
return true;
}
PHP
<?php
$host=""; // Host name
$user=""; // Mysql username
$pswd=""; // Mysql password
$db="pet_home"; // Database name
//$tbl_name="users"; // Table name
$conn = mysql_connect($host, $user, $pswd);
mysql_select_db($db, $conn);
$username=$_POST['username'];
$password=$_POST['password'];
$result=mysql_query("select * from users where username='$username' and
password='$password'")or die (mysql_error());
$count=mysql_num_rows($result);
$row=mysql_fetch_array($result);
if ($count > 0){
echo "\n";
echo $row['filter_st'];
echo "\n";
echo $row['heat_st'];
echo "\n";
echo $row['led_st'];
}else{
echo 0;
}
?>
Just echo the single field then, no parsers, no JSON no nothing...
for example if you want 'heat_st': (just one echo, since the echo is the response you phone gets)
echo $row['heat_st'];
Then the response to your android app will be just that one String which is the result you wanted.( you can easily convert it to int for example in Java if you need to )
if you need multiple fields, JSON is the way to go.
I am new to android development. As part of a bigger project I want to insert data from an android device to a web-server. So I did some research and articles like The article from androidhive and this article from codeproject were really helpful in trying to develop a test-app which inserts in to a mysql db, which is residing at a remote web-server.
Here is my android code
ConnectivityManager connMgr = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected()){
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://xxxxxxxx.in/installment.php");
try{
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("name", editTextCustomer.getText().toString()));
nameValuePairs.add(new BasicNameValuePair("amount", editTextAmount.getText().toString()));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
InputStream is = entity.getContent();
Log.i("postData", response.getStatusLine().toString());
}catch(Exception e){
Log.e("log_tag", "Error in http connection"+e.toString());
}
}
else {
Toast.makeText(PayBillActivity.this, "Internet Access, Denied!!", Toast.LENGTH_LONG).show();
}
Here is the 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['name']) && isset($_POST['amount'])) {
$name = $_POST['name'];
$amount = $_POST['amount'];
$con=mysqli_connect("localhost","db_user","passwd","db_name");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql="INSERT INTO installment (name, amount) VALUES ('$_POST[name]','$_POST[amount]')";
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
echo "1 record added";
// check if row inserted or not
if ($sql) {
// successfully inserted into database
$response["success"] = 1;
$response["message"] = "Installment made successfully";
// echoing JSON response
echo json_encode($response);
} else {
// failed to insert row
echo $result;
$response["success"] = 0;
$response["message"] = "Oops! An error occurred.";
// echoing JSON response
echo json_encode($response);
}
} else {
// required field is missing
//$amount = 1000;
//echo $amount;
$response["success"] = 0;
$response["message"] = "Required field(s) is missing";
// echoing JSON response
echo json_encode($response);
}
?>
when I run the app, I am getting this "NetworkOnMainThreadException" exception and as a result no rows are being added. But its working perfect with HTML POST.
Can anyone tell me where the problem is in my code?
Thanks in advance!:)
I think if you spent the time you did on posting this question into google you may have got some good answers... Just to complete this question
There are two options available with you, either you can add a line of code and allow network operation on main thread, but its very very bad for your app and also as a coding style.
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
The longer option is to redesign the code to have the network operations performed in a separate thread. This is both good for the app and you will learn how to work on a multi-threaded program.
I think you should not use that strict or take it manually out of main..
Just use a smart premade lib and it is making all for you !
Download : http://loopj.com/android-async-http/
Note: And this lib is even using gzip to compress requests :)