When I read the response, I always receive from PHP the error message: missing parameters in the query.
I know the PHP and query is well 100% because works. Only occurs in this way.
Volley.class
JSONObject params = new JSONObject();
params.put("consulta", "UPDATE Usuarios SET Nombre='AAA' WHERE IdUsuario=1");
//All right
RequestFuture<JSONObject> future = RequestFuture.newFuture();
JsonObjectRequest request = new JsonObjectRequest(Request.Method.POST, URL", params, future, future); //request contains params with de sql sentence. Its well
VolleyS.getInstance(context).mRequestQueue.add(request);
JSONObject response = future.get(10, TimeUnit.SECONDS); //response contains the wrong error and the database isn't changed
if (response.getInt("success") == 0) correctoExterna = false;
else correctoExterna = true;
update.php
if (isset($_REQUEST['consulta'])){
$vConsulta= $_REQUEST['consulta'];
$result = mysql_query($vConsulta);
// mysqli_errno($db) != 0
if ($result)
{
$response["success"] = 1;
$response["message"] = "OK.";
echo json_encode($response);
myqli_commit($db);
mysqli_close($db);
}
else{
$response["success"] = 0;
$response["message"] = "ERROR :".mysqli_error($db);
echo json_encode($response);
mysqli_rollback($db);
mysqli_close($db);
}
}
else {
$response["success"] = 0;
$response["message"] = "ERROR, missing fields to insert";
echo json_encode($response);
mysqli_close($db);
}
Related
yesterday I came across the error mentioned below, so I started looking for similar questions on stackoverflow...but none of them seemed to help:(
My guess is that im getting no response from the server but I cant come up with an idea how to fix that. Im using like the same code in some other activities (of course with other functions) but al of them are working perfectly fine.
The only thing that changed is that I used Update table for the first time but I cant see how that would result in the following error.
I hope you can help me.
The strange thing is if the
$anzahlrows == 1
is true and there is no more error in the php file with the query (like usual) than I get in android:
Register Response: {"success":true,"error_msg":"Sie wurden erfolgreich angelegt!"}
I/jsonResponse: {"success":true,"error_msg":"Sie wurden erfolgreich angelegt!"}
and everything works fine....
This is the error im getting:
org.json.JSONException: End of input at character 0 of
in the line of
JSONObject jsonResponse = new JSONObject(response);
This is the code in android studio:
Response.Listener<String> responseListener = new Response.Listener<String>() {
// this gets called on response
#Override
public void onResponse(String response) {
Log.d("Response:", "Register Response: " + response);
// check for boolean success from php
try {
JSONObject jsonResponse = new JSONObject(response);
Log.i("jsonResponse", jsonResponse.toString());
boolean success = jsonResponse.getBoolean("success");
// if true from php start LoginActivity
if (success){
Toast.makeText(RegisterActivity.this, jsonResponse.getString("error_msg"), Toast.LENGTH_LONG).show();
Intent intent = new Intent(RegisterActivity.this, LoginActivity.class);
RegisterActivity.this.startActivity(intent);
}
// if false build an AlertDialog
else {
Toast.makeText(RegisterActivity.this, jsonResponse.getString("error_msg"), Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
};
// call register request and transfer string username and password
RegisterRequest registerRequest = new RegisterRequest(email, password, matrikelnummer, firstName, surname, responseListener);
RequestQueue queue = Volley.newRequestQueue(RegisterActivity.this);
queue.add(registerRequest);
This is my PHP File:
if (isset($_POST["email"]) or isset($_POST["password"]) or isset($_POST["matrikelnummer"]) or isset($_POST["firstName"]) or isset($_POST["surname"])) {
$email = $_POST["email"];
$password = $_POST["password"];
$matrikelnummer = $_POST["matrikelnummer"];
$firstName = $_POST["firstName"];
$surname = $_POST["surname"];
$query = "SELECT * FROM Users WHERE Matrikelnummer ='$matrikelnummer'";
if ($result=mysqli_query($con,$query)) {
$anzahlrows = mysqli_num_rows($result);
if($anzahlrows == 1) {
$query = "UPDATE Users SET email = '$email' ,password = '$password',firstName = '$firstName', surname = '$surname' WHERE Matrikelnummer = '$matrikelnummer'";
if ($result=mysqli_query($con,$query)) {
$response["success"] = TRUE;
$response["error_msg"] = "Sie wurden erfolgreich angelegt!";
echo json_encode($response);
exit;
} else {
$response["success"] = FALSE;
$response["error_msg"] = "Fehler bei der INSERT SQL Abfrage";
echo json_encode($response);
exit;
}
}
else {
$response["success"] = FALSE;
$response["error_msg"] = "Die angegebene Matrikelnummer ist nicht verfügbar";
echo json_encode($response);
exit;
}
}
else {
$response["success"] = FALSE;
$response["error_msg"] = "Fehler bei der SQL Abfrage";
echo json_encode($response);
exit;
}
}
else {
$response["success"] = FALSE;
$response["error_msg"] = "Required parameters missing!";
echo json_encode($response);
exit;
}
The Log shows following:
D/Response:: Register Response:
W/System.err: org.json.JSONException: End of input at character 0 of
W/System.err: at org.json.JSONTokener.syntaxError(JSONTokener.java:449)
W/System.err: at org.json.JSONTokener.nextValue(JSONTokener.java:97)
W/System.err: at org.json.JSONObject.<init>(JSONObject.java:156)
.
.
.
I usually create a response in my PHP code before my code enters the if (isset($_POST["email"]) code starts. Then at each if/else statement I create an appropriate response-- just as you have, with the exception that I do not echo the response and exit. My final statement is where I use the echo response such that it will echo my response regardless of what happens between.
<?php
// array for JSON response
$response = array();
$response["success"] = 0;
$response["message"] = "Error before Parameters";
// check for post data
if (isset($_POST["id"])) {
$id = $_POST['id'];
// include db connect class
require_once __DIR__ . '/db_config.php';
// set vars
$host = DB_SERVER;
$db = DB_DATABASE;
$user = DB_USER;
$pass = DB_PASSWORD;
$charset = 'utf8';
$dsn = "mysql:host=$host;dbname=$db;charset=$charset";
$opt = [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false,
];
// connecting to db
$pdo = new PDO($dsn, $user, $pass, $opt);
$sql = 'SELECT * FROM tblConnectionData WHERE ID = :id;';
$stmt = $pdo->prepare($sql);
$res = $stmt->execute(['id' => $id]);
/* Check the number of rows that match the SELECT statement */
if ($res) {
// success
$response["success"] = 1;
$response["data"] = array();
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$data = array();
$data["id"] = $row["ID"];
$data["state"] = $row["State"];
$data["state_abbrev"] = $row["StateAbbrev"];
$data["city"] = $row["City"];
array_push($response["data"], $data);
}
}
else {
/* No rows matched -- do something else */
// required field is missing
$response["success"] = 0;
$response["message"] = "No data returned!!";
}
}
else {
$response["success"] = 0;
$response["message"] = "Parameters are not correct";
}
// echoing JSON response
echo json_encode($response);
?>
This way I always get a response. I also use int responses for my "success" Tag. That way I can differentiate in my client code what went wrong in by checking the intvalue instead of trying to decipher the string response.
Notice that I am also using PDO with Prepared Statements. I highly recommend that you also use Prepared Statements to prevent SQL Injection.
I fixed it with initializing the array at the start of the php file. It normallt works without in my other php files and I dont know why it fixed my problem but it did.
Thanks for the answers anyway!
Do you see any reasons why it worked this way?
I'm creating app with connection to MySQL Database, I have some working PHP files on my domain already, but now I cannot normally use 1 of PHP files.
The PHP file looks like that :
<?php
$response = array();
require_once __DIR__ . '/db_connect.php';
$db = new DB_CONNECT();
if(isset($_POST['title']) && isset($_POST['dish']) && isset($_POST['review']) && isset($_POST['rating']) && isset($_POST['database_name']) && isset($_POST['UserKeyID']) && isset($_POST['dishphoto']) && isset($_POST['dishsmallphoto'])) {
$title = $_POST['title'];
$dish = $_POST['dish'];
$review = $_POST['review'];
$rating = $_POST['rating'];
$database_name = $_POST['database_name'];
$UserKeyID = $_POST['UserKeyID'];
$dishphoto = $_POST['dishphoto'];
$dishsmallphoto = $_POST['dishsmallphoto'];
$result = mysql_query("INSERT INTO " . $database_name . "(title, review, rating, dish, dishphoto, dishsmallphoto, UserKeyID) VALUES('$title', '$review', '$rating', '$dish', '$dishphoto', '$dishsmallphoto', '$UserKeyID')");
if ($result) {
$response["success"] = 1;
$response["message"] = "Product successfully created.";
// echoing JSON response
echo json_encode($response);
} else {
$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";
// echoing JSON response
echo json_encode($response);
}
?>
In logcat there is something like that :
[socket][/] connected
[CDS]rx timeout:0
[CDS]SO_SND_TIMEOUT:0
>doSendRequest
<doSendRequest
How do i add register validation so that user wont be able to use the same user id as others? I'm stuck here as I have tried every code and nothing would work. And it will crash my app.
I'm using Eclipse to do my app.
My php file
<?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['user_name']) && isset($_POST['user_pwd'])){
$user_name = $_POST['user_name'];
$user_pwd = $_POST['user_pwd'];
// 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 doc_user (user_name, user_pwd) VALUES('$user_name', '$user_pwd')");
// 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);
}
change this part in your code
// connecting to db
$db = new DB_CONNECT();
// chack database
$result = mysql_query("select user_name from doc_user where user_name = '$user_name'");
if(mysql_num_rows($result)){
$response["success"] = 0;
$response["message"] = "username not available.";
// echoing JSON response
echo json_encode($response);
exit;
}
// mysql inserting a new row
$result = mysql_query("INSERT INTO doc_user (user_name, user_pwd) VALUES('$user_name', '$user_pwd')");
how to fix the error:
Undefined variable : id in c:\wamp\www\android_connect\status.php in 38
what i am doing wrong ???
status.php
<?php
ob_start();
session_start();
//array for JSON response
$response = array();
if(isset($_SESSION['id']))
{
$id= $_SESSION['id'];
}
//var_dump ($id);
// include db connect class
require_once '/db_connect.php';
// connecting to db
$db = new DB_CONNECT();
// check for required fields
if(empty($_POST['status'])){
$response["success"] = 0;
$response["message"] = "Your Text Field is empty";
// echoing JSON response
die (json_encode($response));
}
else if (isset($_POST['status'])) {
$status = $_POST['status'];
$sql = mysql_query("INSERT INTO status (status_text, uid)VALUES('$status', '$id')")or die(mysql_error());
if ($sql) {
// successfully inserted into database
$response["success"] = 1;
$response["message"] = "Status Saved.";
// echoing JSON response
die (json_encode($response));
} else {
// failed to insert row
$response["success"] = 0;
$response["message"] = "Error in saving the status.";
// echoing JSON response
die (json_encode($response));
}
}
ob_end_flush();
?>
the error is in the insert query but i do not know how to fix it.
it have something with the $_SESSION can anyone help me ??
The error you get means $id is unset. In your code there isn't a check for the $id variable.
Change else if (isset($_POST['status'])) { to else if (isset($_POST['status']) && isset($id)) {
and add an else statement, something like this:
else {
// failed to insert row because of missing $id
$response["success"] = 0;
$response["message"] = "Error in saving the status, session variable $id missing";
// echoing JSON response
die (json_encode($response));
}
Change the insert query like this,
$sql = mysql_query("INSERT INTO status (status_text, uid)VALUES('".$status."', '".$id."')")or die(mysql_error());
I'm using this simple php code to encode the MySql query result in json format.
But Don't know why it is not giving me the desirable output.
I'm actually trying to get the employee details by entering their 'employee_number'.
<?php
require('DB_Connect.php');
require('config.php');
// check for post data
/*
if (isset($_POST["employee_number"])) {
$employee_name = $_POST['employee_number'];
*/
//get a employee from employee_info table
$result = mysql_query("SELECT *FROM employee_info WHERE employee_number =9876543210");
if (!empty($result)) {
// check for empty result
if (mysql_num_rows($result) > 0) {
$result = mysql_fetch_array($result);
echo("Success !! Yoo");
$employee = array();
$employee["employee_number"] = $result["employee_number"];
$employee["employee_name"] = $result["employee_name"];
$employee["flag"]=$result["flag"];
// success
$response["success"] = 1;
// user node
$response["employee"] = array();
array_push($response["employee"], $employee);
// echoing JSON response
echo json_encode($response);
} else {
// no employee found
$response["success"] = 0;
$response["message"] = "No employee found";
// echo no users JSON
echo json_encode($response);
}
}else {
// no employee found
$response["success"] = 0;
$response["message"] = "No employee found";
// echo no users JSON
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);
?>
mysql_query is deprecated. Use mysqli or PDO instead.
make sure you format your query properly *note the spaces
$result = mysql_query("SELECT * FROM employee_info WHERE employee_number = 9876543210");
you could also just echo the $result as your employee array doesn't seem to do anything.
echo json_encode($result);