Not getting the JSON data in PHP - php

I am creating an android application and submit the user details from Android application to php at server side by JSON. But at server side I am not getting the JSON data. At server side php the JSON comes from android application is seems null. I am using POST method for this. I know that my POST method code is wrong in PHP at server side. But I have no idea to solve this.
Here is my PHP code for getting JSON. Every time I get same message:
Required fields missing
Code:
<?php
/*
* Following code will create a new user row
* All user details are read from HTTP Post Request
*/
// array for JSON response
$response = array();
print_r($_POST);
// check for required fields
if (isset($_POST['Firstname']) && isset($_POST['Lastname']) && isset($_POST['Username']) && isset($_POST['Email']) && isset($_POST['Password']) && isset($_POST['Country']) && isset($_POST['Mobile'])) {
echo('bhargavi');
$Firstname = $_POST['Firstname'];
$Lastname = $_POST['Lastname'];
$Username = $_POST['Username'];
$Email = $_POST['Email'];
$Password = $_POST['Password'];
$Country = $_POST['Country'];
$Mobile = $_POST['Mobile'];
// 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 users(Firstname,Lastname,Username,Email,Password,Country,Mobile) VALUES('$Firstname','$Lastname','$Username','$Email','$Password','$Country','$Mobile')");
// check if row inserted or not
if ($result) {
// successfully inserted into database
$response["success"] = 1;
$response["message"] = "User successfully Registered.";
// 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 {
// required field is missing
$response["success"] = 0;
$response["message"] = "Required field(s) is missing";
// echoing JSON response
echo json_encode($response);
}
?>

Probably you should decode the json string before checking $_POST['Firstname'] etc...
Let's say you send from the app a string called data. On php you should do something like that:
$data = json_decode($_POST['data']);
and then check if $data contains the data you neeed by doing:
if (isset($data->Firstname) && isset($data->Lastname) etc...){
...
...
}
If I can give you an advice it would be better if you check data integrity directly from your app instead of doing it on your server, it would give the chance to spare some server resources...
As Jay Blanchard already mentioned don't use mysql like that or you'll be exposed to mysql injection...

Related

php mysql update code [duplicate]

This question already has answers here:
When to use single quotes, double quotes, and backticks in MySQL
(13 answers)
Closed 6 years ago.
trying to update a database using this code
<?php
/*
* Following code will update a product information
* A product is identified by product id (pid)
*/
// array for JSON response
$response = array();
// check for required fields
if ( isset($_POST['name']) && isset($_POST['username']) && isset($_POST['password']) && isset($_POST['phone']) && isset($_POST['email'])&& isset($_POST['licno'])&& isset($_POST['licdate'])&& isset($_POST['meddate'])&& isset($_POST['flighttime'])&& isset($_POST['income'])&& isset($_POST['costs'])&& isset($_POST['pending'])&& isset($_POST['nextpayment'])&& isset($_POST['total'])) {
$name = $_POST['name'];
$username = $_POST['username'];
$password = $_POST['password'];
$phone = $_POST['phone'];
$email = $_POST['email'];
$licno = $_POST['licno'];
$licdate = $_POST['licdate'];
$meddate = $_POST['meddate'];
$flighttime = $_POST['flighttime'];
$income = $_POST['income'];
$costs = $_POST['costs'];
$pending = $_POST['pending'];
$nextpayment = $_POST['nextpayment'];
$total = $_POST['total'];
define('DB_USER', ""); // db user
define('DB_PASSWORD', ""); // db password (mention your db password here)
define('DB_DATABASE', ""); // database name
define('DB_SERVER', ""); // db server
// array for JSON response
$conn = new mysqli(DB_SERVER, DB_USER, DB_PASSWORD,DB_DATABASE);
$sql = "UPDATE login SET username = '$username', password = '$password', phone = '$phone', email = '$email', license = '$licno', expiration = '$licdate', meddate = '$meddate', flighttime = '$flighttime', income = '$income', costs = '$costs', pending = '$pending', nextpayment = '$nextpayment', total = '$total' WHERE name = $name";
$result = $conn->query($sql) or die (mysqli_connect_error());
// mysql update row with matched pid
// check if row inserted or not
if ($result) {
// successfully updated
$response["success"] = 1;
$response["message"] = "Patient details 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);
}
?>
i get no response and the db doesnt update, i dont know whats wrong, im sure im sending all parameters and the name im sending corresponds with the name in the db
in android studio i get this error msg
org.json.JSONException: End of input at character 0 of
i know the mistake is not in android studio, its somewhere in this php cause i get the same eror if i do it with postman
Database parameters are blank in this post but not in the real code , so thats not the problem either
At the end of the query, change WHERE name = $name"; to WHERE name = '$name'";
Define your database details. Right now its blank.
define('DB_USER', ""); // db user empty
define('DB_PASSWORD', ""); // db password empty
define('DB_DATABASE', ""); // database name
define('DB_SERVER', ""); // db server empty
Also recommend don't define your database details openly.

PHP post through URL parameters

I am trying to do php post to mysql databse using a android app and a website url.
But I do not know how to make a post request through a url.
I tried http://localhost/api/create_product.php?name=chetan&price=2000&description=someDescription
This returns required fields missing.
Maybe the url I'm trying to pass is incorrect
Help me to know that how do I do a post in DB using URL that returns JSON for success.
<?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['price']) && isset($_POST['description'])) {
$name = $_POST['name'];
$price = $_POST['price'];
$description = $_POST['description'];
// 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 products(name, price, description) VALUES('$name', '$price', '$description')");
// 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 {
// required field is missing
$response["success"] = 0;
$response["message"] = "Required field(s) is missing";
// echoing JSON response
echo json_encode($response);
}
?>
DB_CONNECT() is working fine as I am able to do a GET query successfully
http://localhost/api/create_product.php?name=chetan&price=2000&description=someDescription => This is a request with GET parameters and your statement here :
if (isset($_POST['name']) && isset($_POST['price']) && isset($_POST['description'])) {
Are checking for POST parameters, either you change every $_POST by $_GET, either you change your method of passing arguments cause usually when you give arguments to put it in a database it's through POST and not GET for security reasons. GET parameters are used to read something but not insert.

Login system: $_POST['username'] and $_POST['password'] are always empty

Let me first start by saying that I have searched endlessly on Google for help and have literally spent the past x hours debugging the same error but I just can't figure it out.
I am following this tutorial on how to create a login system for my Android app. When I run my app on Genymotion, I am able to enter my login credentials but as soon as I hit the login button my app crashes. I ran my app again in debug mode and the cause of this was because of the following exception:
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String org.json.JSONObject.toString()' on a null object reference
Correct me if im wrong, but I think what is happening is that my JSONParser is trying to parse an empty object. This could be because my PHP file is always returning empty and I don't know why that is.
if(isset($_POST['username'])) {
$password=$_POST["username"];
}
if(isset($_POST['password'])) {
$password=$_POST["password"];
}
if (!empty($_POST))
{
if (empty($_POST['username']) || empty($_POST['password']))
{
// Create some data that will be the JSON response
$response["success"] = 0;
$response["message"] = "One or both of the fields are empty .";
//die is used to kill the page, will not let the code below to be executed. It will also
//display the parameter, that is the json data which our android application will parse to be
//shown to the users
die(json_encode($response));
}
$query = " SELECT * FROM login WHERE username = '$username'and password='$password'";
$sql1=mysql_query($query);
$row = mysql_fetch_array($sql1);
if (!empty($row))
{
$response["success"] = 1;
$response["message"] = "You have been sucessfully login";
die(json_encode($response));
}
else
{
$response["success"] = 0;
$response["message"] = "invalid username or password ";
die(json_encode($response));
}
}
else
{
$response["success"] = 0;
$response["message"] = " One or both of the fields are empty ";
die(json_encode($response));
}
I think you forgot to set the JSON header.
If you are returning JSON , You need to change the code like this
$data = $response;
header('Content-Type: application/json');
echo json_encode($data);

Insert query not working in WAMP Server

We have one android application which access WAMP Server using PHP. All queries like, Select* etc working fine. But insert query not working properly in specific condition,
When WAMP already have some data in database we failed to insert new data in database. But when WAMP server don't have any existing data then insert query work successfully. following is PHP code we are using to insert a data,
<?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['UserName']) && isset($_POST['UserID']) && isset($_POST['Password']) && isset($_POST['Age'])&& isset($_POST['ContactNumber']) && isset($_POST['expiryDate'])) {
$UserName = $_POST['UserName'];
$UserID = $_POST['UserID'];
$Password = $_POST['Password'];
$Age = $_POST['Age'];
$ContactNumber = $_POST['ContactNumber'];
$expiryDate = $_POST['expiryDate'];
// 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 normaluser(UserName, UserID, Password,Age,ContactNumber,expiryDate) VALUES('$UserName', '$UserID', '$Password','$Age','$ContactNumber','$expiryDate')");
// check if row inserted or not
if ($result) {
// successfully inserted into database
$response["success"] = 1;
$response["message"] = "New user successfully created.";
// echoing JSON response
echo json_encode($response);
} else {
// failed to insert row
$response["success"] = 0;
$response["message"] = "Oops! error is there.";
// echoing JSON response
echo json_encode($response);
}
} else {
// required field is missing
$response["success"] = 0;
$response["message"] = "Required fields is missing";
// echoing JSON response
echo json_encode($response);
}
?>
Can you guys please help use to solved this problem?
Ignoring the using of mysql_* which is deprecated and lack of sanitization of data.
You do not check if this User is already on the database. Assuming at least one of your columns is a unique or Primary key then this query is likely to fail if you try and create the same user twice.
But regardless of that possible issue if you add some useful error processing to your code you will be told exactly what the problem is. This is a little simplistic as you probably dont want these errors sent back to a user but it will tell you the exact error being returned from MySQL:
$result = mysql_query("INSERT INTO normaluser(UserName, UserID, Password,Age,ContactNumber,expiryDate)
VALUES('$UserName', '$UserID', '$Password','$Age','$ContactNumber','$expiryDate')");
// check if row inserted or not
if ($result) {
// successfully inserted into database
$response["success"] = 1;
$response["message"] = "New user successfully created.";
// echoing JSON response
echo json_encode($response);
} else {
// failed to insert row
$response["success"] = 0;
$response["message"] = 'Database error ' . mysql_errno() . ' ' . mysql_error();
// echoing JSON response
echo json_encode($response);
}

_POST method returns ??? when request utf8 characters

i have the following problem... i am building an android app and i regeuest text formated in utf8 (greek chars) from editTexts by using the POST method. The POST method gets the greek chras from the editTexts as '???' and insert them in mysal again as '???'
How will the POST recognize my greek chars???
<?php
// PHP variable to store the host address
$db_host = "localhost";
// PHP variable to store the username
$db_uid = "lolen";
// PHP variable to store the password
$db_pass = "lolen";
// PHP variable to store the Database name
$db_name = "lolen";
// PHP variable to store the result of the PHP function 'mysql_connect()' which establishes the PHP & MySQL connection
$db_con = mysql_connect($db_host,$db_uid,$db_pass) or die('could not connect');
mysql_query("SET character_set_results=utf8", $db_con);
mb_language('uni');
mb_internal_encoding('UTF-8');
mysql_select_db($db_name, $db_con);
mysql_query("set names 'utf8'",$db_con);
// array for JSON response
$response = array();
// check for required fields
if (isset($_POST['k_p']) )
{
$Kwdikos_Proiontos=$_POST['k_p'];
$Proion=$_POST['p'];
$Kwdikos_Tupou=$_POST['k_t'];
//$Tupos=$_POST['t'];
$sql=mysql_query("SELECT * FROM tupoi WHERE Kwdikos_Tupou LIKE '". $_POST["k_t"]."'", $db_con);
while($row = mysql_fetch_array($sql))
{
$output[]=$row['Tupos'];
$re= json_encode($output[0]);
$dd= json_decode($re, true);
}
$result =mysql_query("INSERT INTO proionta(Kwdikos_Proiontos, Proion, Kwdikos_Tupou, Tupos) VALUES('$Kwdikos_Proiontos', '$Proion', '$Kwdikos_Tupou', '$dd')");
//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
{
// required field is missing
$response["success"] = 0;
$response["message"] = "Required field(s) is missing";
// echoing JSON response
echo json_encode($response);
}
?>
ps. my db is already in utf8 cause i display and add other data in greek, by using SELECT , INSERT, in the db.
Finally i found a solution to my problem, i used GET method instead of POST, and now it works correctly! Thnx for the sql injection tips, i will read more about this issue!

Categories