unable to get proper reply from PHP to android - php

I am creating an app for which I have to maintain a table(login registration), for connecting my android app to the table I am using PHP.
Android code
try {
JSONObject jsonResponse = new JSONObject(response);
boolean success = jsonResponse.getBoolean("success");
if (success) {
Intent intent = new Intent(RegisterActivity.this, Login.class);
RegisterActivity.this.startActivity(intent);
} else if(!success)
{ JSONObject jsonResponse2 = new JSONObject(response);
String errval = new String();
errval=jsonResponse2.getString("errval");
AlertDialog.Builder builder = new AlertDialog.Builder(RegisterActivity.this);
builder.setMessage(errval)
.setNegativeButton("retry", null)
.create()
.show();
}
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(), "Error submitting registration", Toast.LENGTH_SHORT).show();
}
PHP code:-
require 'config.php';
$file = 'outfile.txt';
if ($_POST) {
file_put_contents($file,"~~~~~~~~~~~~~~~~~~~~\n");
foreach ($_POST as $KEY => $VAL) {
file_put_contents($file,$KEY."=>".$VAL."\n", FILE_APPEND);
}
if (#$_POST["Email_id"] and #$_POST["hash"]) {
$email = strtolower($_POST["Email_id"]);
$username = strtolower($_POST["Username"]);
$hash = $_POST["hash"];
$echk = $my->Execute("select count(*) from users where email = '$email'");
if ($echk->fields[0] == 0) {
$uchk = $my->Execute("select count(*) from users where user = '$username'");
if ($uchk->fields[0] == 0) {
$ins = $my->Execute("insert into users values (default,'$username','$email','$hash',default)");
$error["success"] = true;
$error["errval"] = "success";
file_put_contents($file,"success", FILE_APPEND);
} else {
$error["success"] = false;
$error["errval"] = "User: $username already exists";
}
} else {
$error["success"] = false;
$error["errval"] = "Email: $email already exists";
}
} else {
$error["errval"] = "Missing a key: 'Email_id' or 'hash'";
}
file_put_contents($file,"~~~~~~~~~~~~~~~~~~~~\n", FILE_APPEND);
$json = json_encode($error);
print_r($json);
}
?>
The details are being entered in the DB without any issues every time, the code also shows if the email is aldready existing in the table, but if the registration is a success, the app throws exception Error submitting registration. cant figure out where the problem is
thank you.
PS. I am new to stackoverflow still learning, forgive if there are any mistakes in post

if (#$echk->fields[0] == 0) {
$uchk = $my->Execute("select count(*) from users where user = '$username'");
if (#$uchk->fields[0] == 0) {
$ins = $my->Execute("insert into users values (default,'$username','$email','$hash',default)");
$error["success"] = true;
$error["errval"] = "success";
file_put_contents($file,"success", FILE_APPEND);
forgot # in if condition

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)
}
}
}

org.json.JSONException: End of input at character 0 of with volley and php

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?

Android PostResponseAsyncTask cant get string from android

I have this application where I use PHP and Mysql for my queries in android studio but when im using update its not working the php should give me the string of what the $result gives me but its not giving any its blank.
Here are my codes.
Android
HashMap postData = new HashMap();
if (TextUtils.isEmpty(etCarModel.getText().toString())) {
Toast.makeText(UpdateClick.this, "Car model is empty", Toast.LENGTH_SHORT).show();
return;
}
if (TextUtils.isEmpty(etCarType.getText().toString())) {
Toast.makeText(UpdateClick.this, "Car type is empty", Toast.LENGTH_SHORT).show();
return;
}
if (TextUtils.isEmpty(etCapacity.getText().toString())) {
Toast.makeText(UpdateClick.this, "Capacity is empty", Toast.LENGTH_SHORT).show();
return;
}
if (TextUtils.isEmpty(etPlateNumber.getText().toString())) {
Toast.makeText(UpdateClick.this, "Plate Number is empty", Toast.LENGTH_SHORT).show();
return;
}
if (TextUtils.isEmpty(etPrice.getText().toString())) {
Toast.makeText(UpdateClick.this, "Price is empty", Toast.LENGTH_SHORT).show();
return;
}
postData.put("txtCar_No", tvCar_No.getText().toString());
postData.put("txtCarModel", etCarModel.getText().toString());
postData.put("txtCarType", etCarType.getText().toString());
postData.put("txtCapacity", etCapacity.getText().toString());
postData.put("txtPlateNumber", etPlateNumber.getText().toString());
postData.put("txtCarPrice", etPrice.getText().toString());
postData.put("image", toString());
postData.put("txtFuelType", spFuelType.getSelectedItem().toString());
PostResponseAsyncTask taskUpdate = new PostResponseAsyncTask(UpdateClick.this, postData, new AsyncResponse() {
#Override
public void processFinish(String q) {
Log.d(TAG,q);
if(q.contains("success")){
Toast.makeText(UpdateClick.this, "Car details updated!", Toast.LENGTH_SHORT).show();
Intent in = new Intent(UpdateClick.this, OwnerTabs.class);
startActivity(in);
finish();
}else{
Toast.makeText(getApplicationContext(), "Error ? " + q.toString(), Toast.LENGTH_SHORT).show();
}
}
});
taskUpdate.execute("http://carkila.esy.es/update.php");
}
PHP
<?php
include_once("connection.php");
if(isset($_POST['txtCar_No']) && isset($_POST['txtCarModel']) &&
isset($_POST['txtCarType']) && isset($_POST['txtCapacity']) &&
isset($_POST['image']) && isset($_POST['txtFuelType']) &&
isset($_POST['txtPlateNumber']) && isset($_POST['txtcarPrice']))
{
$now = DateTime::createFromFormat('U.u', microtime(true));
$id = $now->format('YmdHis');
$upload_folder = "upload";
$path = "$upload_folder/$id.jpeg";
$fullpath = "http://carkila.esy.es/$path";
$image = $_POST['image'];
$Car_No = $_POST['txtCar_No'];
$Car_Model = $_POST['txtCarModel'];
$Car_Type = $_POST['txtCarType'];
$Capacity = $_POST['txtCapacity'];
$Fuel_Type = $_POST['txtFuelType'];
$PlateNumber = $_POST['txtPlateNumber'];
$carPrice = $_POST['carPrice'];
$query = "UPDATE tbl_cars SET Car_Model='$Car_Model', Car_Type='$Car_Type', Capacity='$Capacity', Image='$fullpath', fuelType='$Fuel_Type',carPlatenuNumber='$PlateNumber' ,carPrice= '$carPrice' WHERE 'Car_No'=$Car_No";
$result = mysqli_query($conn,$query);
$count = mysqli_affected_rows($conn);
if($result == TRUE && $count > 0){
echo "success";
exit();
}else{
print_r (mysqli_error($conn));
echo "failed";
exit();
}
}
?>
i am from mobile, but try to change $result:
$result = mysqli_query($conn,$query);
With this:
$result = mysqli_query($conn,$query) or die(mysqli_error($conn));
EDIT:
You have to check whether the information is sent, so try to insert it to your code:
$filename = "log.txt";
$fh = fopen($filename, "a") or die("Could not open log file.");
$post = var_dump($post);
fwrite($fh, date("d-m-Y, H:i")." - $post\n") or die("Could not write file!");
fclose($fh);
Dont forget to create a log.txt file with chmod 777

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?

org.json.JSONException: Value <br of type java.lang.String cannot be converted to JSONObject

I m trying to do a registration page from an android activity connectiong the datas to my sqldatabase, I m getting this error " org.json.JSONException: Value
First of all, could anyone advise me on how to debug my program when using an mysql database with php script for an android application ? Cause I usually use the log cat but here the errors aren't as clear :S ...
Here is the activity code :
public class Subscribe extends Activity {
Button bSubscribe;
EditText etPwdSub, etPwdConf, etLoginSub, etNameSub, etFnSub;
String result = null;
InputStream is = null;
String donnees = "";
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.subscribe);
etLoginSub = (EditText) findViewById(R.id.etLoginSub);
etPwdSub = (EditText) findViewById(R.id.etPwdSub);
etPwdConf = (EditText) findViewById(R.id.etPwdConf);
etNameSub = (EditText) findViewById(R.id.etNameSub);
etFnSub = (EditText) findViewById(R.id.etFnSub);
bSubscribe = (Button) findViewById(R.id.bSubscribe);
bSubscribe.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Pattern p = Pattern.compile(".+#.+\\.[a-z]+");
Matcher m = p.matcher(etLoginSub.getEditableText());
if (m.matches() == false) {
Toast.makeText(
getBaseContext(),
"Le champs email ne correspond pas au format d'une adresse mail",
Toast.LENGTH_SHORT).show();
} else {
// autre méthode : etPwdSub.equals("")
if (etPwdSub.getEditableText() != null
&& etPwdConf.getEditableText() != null
&& etNameSub.getEditableText() != null
&& etFnSub.getEditableText() != null) {
if (etPwdSub.getEditableText().toString().equals(etPwdConf.getEditableText().toString())) {
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("login", etLoginSub.getText().toString()));
nameValuePairs.add(new BasicNameValuePair("pwd", etPwdConf.getText().toString()));
nameValuePairs.add(new BasicNameValuePair("name", etNameSub.getText().toString()));
nameValuePairs.add(new BasicNameValuePair("firstname", etFnSub.getText().toString()));
try {
// commandes httpClient
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(
"http://192.168.1.101/spotnshare/subscribe.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
} catch (Exception e) {
Log.i("taghttppost", "" + e.toString());
Toast.makeText(getBaseContext(), e.toString(), Toast.LENGTH_LONG)
.show();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "UTF-8"));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result = sb.toString();
} catch (Exception e) {
Log.i("tagconvertstr", "" + e.toString());
}
try {
JSONObject jObj = new JSONObject(result);
donnees = jObj.getString("message");
Intent ourIntent = new Intent(Subscribe.this,
SubscribeMess.class);
// objet qui vas nous permettre de passe des variables ici la
// variable passInfo
Bundle objetbunble = new Bundle();
objetbunble.putString("message", donnees);
ourIntent.putExtras(objetbunble); // on passe notre objet dans l'intent
// on appelle notre activité
startActivity(ourIntent);
} catch (JSONException e) {
Log.i("tagjsonexp", "" + e.toString());
} catch (ParseException e) {
Log.i("tagjsonpars", "" + e.toString());
}
} else {
Dialog d = new Dialog(Subscribe.this);
d.setTitle(etPwdSub.getEditableText() +" "+etPwdConf.getEditableText());
d.show();
}
} else {
Dialog d = new Dialog(Subscribe.this);
d.setTitle("Fill in all the fields !");
d.show();
}
}
}
});
}
protected void onPause() {
super.onPause();
finish();
}
}
and here is the php script :
<?php
if( isset($_POST['login']) && isset($_POST['pwd']) && isset($_POST['name']) && isset($_POST['firstname'])) {
include("connexion_bdd.php");
if(connexionBDD() == 1){
$login = $_POST['login'];
$pwd = $_POST['pwd'];
$name = $_POST['name'];
$firstname = $_POST['firstname'];
$sql = "SELECT colUserID
FROM userTable
WHERE colUserLogin = '".$login."' ";
$req = mysql_query($sql);
$resultat=mysql_num_rows($req);
if($resultat==0){
$temps = time();
$clef = md5($login . $temps);
$req = mysql_query("INSERT INTO userTable(colUserLogin, colUserPwd, colUserName, colUserFirstname, colUserKey, colUserDate)
VALUES( '$login', '$pwd', '$name', '$firstname', '$clef', '$temps')");
if($req){
$destinataire = $login;
$sujet ="Welcome on SnSR";
$from = "From: SpotnShareReminder#live.com \r\n";
$from .= "Content-Type: text/html; charset=us-ascii\r\n";
$message = ' Clic on the link below :<br/>
<a href="http://localhost/spotnshare/validation_mail.php?usrk='.$clef.' ">
Registration confirmation.
</a> ';
ini_set('SMTP','relay.skynet.be');
if(mail($destinataire,$sujet,$message,$from)){
$msg = 'Check your mailbox to activate your account !';
}
else{
$msg = 'Problem sending you the activation mail !';
$req = mysql_query("DELETE FROM userTable WHERE colUserLogin = '".$pseudo."' ");
}
}
else{
$msg = 'Problem inserting you in our database !';
}
}else{
$msg = 'This email has already been used !';
}
mysql_free_result ($req);
}else{
$msg = "Connexion problem with de DB"
print(json_encode(array("message" => $msg)));
}
}else{
$msg = "Couldn't treat your datas"
}
print(json_encode(array("message" => $msg)));
?>
Your request to http://192.168.1.101/spotnshare/subscribe.php is failing and returning a non-JSON string (probably a PHP error). You can print out the value with a
Log.i("tagconvertstr", "["+result+"]");
before the new JSONObject call to see what you're getting before parsing it.
EDIT: if you are using Eclipse you can set a break point and step through to see what's going on.
Thanks I manage to correct some of the errors 2 ';' were missing and I could see the error with Log.i("tagconvertstr", "["+result+"]");
The msg that it is showing is something like that :
[<br/ > font size = 1 table class=''xdebug-erroe' dir='ltr' ... loads of html code that wasn't in my initial code then....{"message":"Problem sending you the activation mail !"}]
So there's a problem with the json format on that message "Problem sending you the activation mail" but the user was registered OK!
So the second time i would try that code it would show me in a correct json format : "This email has already been used" ! (without any errors) but i still can't find the error in my php code : S
try preventing any output before your print and change the print to echo
you may also remove the closing ?> to prevent further output after the php script
<?php
ob_start();
if( isset($_POST['login']) && isset($_POST['pwd']) && isset($_POST['name']) && isset($_POST['firstname'])) {
include("connexion_bdd.php");
if(connexionBDD() == 1){
$login = $_POST['login'];
$pwd = $_POST['pwd'];
$name = $_POST['name'];
$firstname = $_POST['firstname'];
$sql = "SELECT colUserID
FROM userTable
WHERE colUserLogin = '".$login."' ";
$req = mysql_query($sql);
$resultat=mysql_num_rows($req);
if($resultat==0){
$temps = time();
$clef = md5($login . $temps);
$req = mysql_query("INSERT INTO userTable(colUserLogin, colUserPwd, colUserName, colUserFirstname, colUserKey, colUserDate)
VALUES( '$login', '$pwd', '$name', '$firstname', '$clef', '$temps')");
if($req){
$destinataire = $login;
$sujet ="Welcome on SnSR";
$from = "From: SpotnShareReminder#live.com \r\n";
$from .= "Content-Type: text/html; charset=us-ascii\r\n";
$message = ' Clic on the link below :<br/>
<a href="http://localhost/spotnshare/validation_mail.php?usrk='.$clef.' ">
Registration confirmation.
</a> ';
ini_set('SMTP','relay.skynet.be');
if(mail($destinataire,$sujet,$message,$from)){
$msg = 'Check your mailbox to activate your account !';
}
else{
$msg = 'Problem sending you the activation mail !';
$req = mysql_query("DELETE FROM userTable WHERE colUserLogin = '".$pseudo."' ");
}
}
else{
$msg = 'Problem inserting you in our database !';
}
}else{
$msg = 'This email has already been used !';
}
mysql_free_result ($req);
}else{
$msg = "Connexion problem with de DB"
print(json_encode(array("message" => $msg)));
}
}else{
$msg = "Couldn't treat your datas"
}
ob_end_clean()
echo(json_encode(array("message" => $msg)));
You should set Content-Type header before sending back the response.
header('Content-Type: application/json');
print(json_encode(array("message" => $msg)));
Check this : Returning JSON from a PHP Script
I have the same problem; i found the solution the easy way.
In Java code just type Log.e("anyText",response);
In logCat it will show you what is problem

Categories