I have successfully fetched data from remote database using methods posted on internet.But I'm unable to push (insert) data into the same table.
I've added a static counter just to check whether the code reaches the given url, but as expected , it fails.Below is the php file I've saved up in my remote server file manager.
<?php
$json=$_GET [ 'json']; $json=f ile_get_contents( 'php://input');
$obj=json_decode($json);
$conn=mysql_connect( "mydatabasename", "myusername", "mypassword") or die( "error connecting");
mysql_select_db( "mydatabasename",$conn)or die("database couldnot connect");
error_reporting(E_ALL);
$tid=$_POST[ 'tid'];
$name=$_POST[ 'name'];
mysql_query( "insert into mytablename(tid,name) values($tid,$name)");
?>
I took two inputs in the android layout, tid, name and trying to send to remote database.
Note : database name and other details have been hidden for security purpose.
if your looking for a clean way ..i suggest you to do something like this :
register.php
<?php
include('connect.php');
$response = array();
if (isset($_POST['Nom']) && isset($_POST['Prenom']) && isset($_POST['Email'])&& isset($_POST['Mdp'])) { //checking if the required fields are set
$Nom = $_POST['Nom'];//the family name
$Prenom = $_POST['Prenom']; //last name
$Email = $db->real_escape_string($_POST['Email']);
$Mdp = $db->real_escape_string($_POST['Mdp']); //the password
if ($res = $db->query("SELECT * FROM `patient` WHERE `Email_p`='$Email' ")) {
$row_cnt = $res->num_rows; }
if($row_cnt>0) {
$response["success"] = 0;
$response["message"] = "Email exists"; }
if ($row_cnt <1){
$result = mysqli_query($db,"INSERT INTO `patient`(`Id_p`, `Nom`, `Prenom`, `Email_p`, `Mdp`) VALUES ('','$Nom','$Prenom','$Email','$Mdp')");
if ($result ) {
$response["success"] = 1; // if account created we set success value to 1
$response["message"] = "account created";
} else {
$response["success"] = 0;
$response["message"] = "Oops Error";
}}
}else {
$response["success"] = 0;
$response["message"] = "Fields messing";
}
echo json_encode($response);
?>
in android ... yourActivity.java
class CreerNouveauCompte extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(inscription.this);
pDialog.setMessage(getString(R.string.inscriEnCours));
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
protected String doInBackground(String... args) {
String nom = edtNom.getText().toString();
String prenom = edtPrenom.getText().toString();
String email = edtEmail.getText().toString();
String mdp = edtMdp.getText().toString();
JSONObject json;
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("Nom", nom));
params.add(new BasicNameValuePair("Prenom", prenom));
params.add(new BasicNameValuePair("Email", email));
params.add(new BasicNameValuePair("Mdp", mdp));
json= jsonParser.makeHttpRequest(url_register (your url),
"POST", params);
}
try {if(json != null && !json.isNull("success")){
int success = json.getInt("success");
s2=json.getString("message");
if (success == 1) { //the acount created
Intent intent;
SharedPreferences settings = getSharedPreferences("compte", 0);
SharedPreferences.Editor editor = settings.edit();
editor.putString("nom",edtNom.getText().toString() );
editor.putString("prenom",edtPrenom.getText().toString() );
editor.putString("email",edtEmail.getText().toString());
editor.putString("mdp",edtMdp.getText().toString());
editor.apply();
intent = new Intent(inscription.this,MainActivity.class);
}
startActivity(intent);
finish();
} else {
}}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String file_url) {
pDialog.dismiss();
}
}
call it like this
new CreerNouveauCompte().execute();
the connect.php
<?php
$db = new mysqli('localhost', 'root', '', 'rechmed');
mysqli_set_charset($db,'utf8');
?>
//note i use mysqli ..in your case use mysql
Use the code below if you are trying to decode a JSONObject with this format {"tid":"myTidValue", "name":"myNameValue"}
<?php
$json=stripslashes($_GET['json']);
$obj=json_decode($json, true);
$conn=mysql_connect( "mydatabasename", "myusername", "mypassword") or die( "error connecting");
mysql_select_db( "mydatabasename",$conn)or die("database couldnot connect");
error_reporting(E_ALL);
$tid=$json['tid'];
$name=$json['name'];
mysql_query("insert into mytablename(tid,name) values('$tid','$name')");
?>
and to decode a JSONArray with this format [{"tid":"myTidValue1", "name":"myNameValue1"}, {"tid":"myTidValue2", "name":"myNameValue2"}] you can use below code
<?php
$json=stripslashes($_GET['json']);
$obj=json_decode($json, true);
$conn=mysql_connect( "mydatabasename", "myusername", "mypassword") or die( "error connecting");
mysql_select_db( "mydatabasename",$conn)or die("database couldnot connect");
error_reporting(E_ALL);
foreach ($json as $data){
$tid=$data['tid'];
$name=$data['name'];
mysql_query("insert into mytablename(tid,name) values('$tid','$name')");
}
?>
if neither works, post your codes for android
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 have an app that sends some information via POST to a php script in a server. It uses Asynchttpclient. How can I also receive a reply back from the server (via json?)? Please help.
This is my php script
if($_POST["mode"]=="newuser"){
//$gcmRegID = $_GET["shareRegId"];
$gcmRegID = $_POST["regID"];
$gcmUserName = $_POST["userName"];
$gcmFolderName = $_POST["folderName"];
$gcmDate = date("d/m/y");
$conn = new mysqli($servername, $username, $password, $dbname);
if($conn->connect_error){
die("Connection failed: " . $conn->connect_error);
}
$in_user = "user";
$in_password = "NULL";
$in_email = "NULL";
$in_dob = "NULL";
$in_role = "user";
$in_datejoined = "0000-00-00";
$foldername = "NULL";
$sql = "INSERT INTO user(password,regid,name,email,phone,dob,role,datejoined,foldername) VALUES('$in_password','$gcmRegID','$gcmUserName','$in_email','$in_phone','$in_dob','$in_role','$gcmDate','$foldername')";
$substringtitle = substr($gcmRegID,-7);
$combined = $gcmUserName."_".$substringtitle;
if($conn->query($sql)===TRUE){
mkdir("./users/".$gcmFolderName);
$newfoldername = "./users/".$gcmFolderName;
$updatequery = "UPDATE user SET foldername='$newfoldername' WHERE name='$gcmUserName'";
$returnfield = array(
'foldername' => $newfoldername
);
header('Content-type: application/json');
echo json_encode(array('returnfield'=>$returnfield));
if($conn->query($updatequery)===TRUE){
echo "folder updated";
}
//echo "Folder created!";
//}
echo "New record created successfully";
}else{
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
echo "Done!";
exit;
}
Android code
//store in the file server (PHP)
private void storeREG(final String registerID,String userName,String folderName){
pg.show();
params.put("regID", registerID);
params.put("userName",userName);
params.put("folderName", folderName);
params.put("mode","newuser");
Log.d("STORE","STORE");
//Make RESTful webservice call
AsyncHttpClient client = new AsyncHttpClient();
client.post(AppConstants.SERVER_URL, params, new AsyncHttpResponseHandler() {
#Override
public void onSuccess(String content) {
pg.hide();
if (pg != null) {
pg.dismiss();
}
Toast.makeText(applicationCtx, "ID sharing successful", Toast.LENGTH_LONG).show();
Intent home = new Intent(applicationCtx, HomeActivity.class);
home.putExtra("regID", registerID);
Log.d("REGID", registerID);
startActivity(home);
finish();
}
#Override
public void onFailure(int statusCode, Throwable error, String content) {
pg.hide();
if (pg != null) {
pg.dismiss();
}
Log.d("ERRORTHROW", error.toString());
if (statusCode == 404) {
Toast.makeText(applicationCtx, "Requested resource not found", Toast.LENGTH_LONG).show();
} else if (statusCode == 500) {
Toast.makeText(applicationCtx, "Something went wrong at the server", Toast.LENGTH_LONG).show();
} else {
Log.d("SHOWME", String.valueOf(statusCode));
Toast.makeText(applicationCtx, "Unexpected error occurred", Toast.LENGTH_LONG).show();
}
}
});
}
Hopefully I can get help with this.
You may try to revise your PHP Code. Below is a well-commented sample code to get you started:
<?php
// EXPLICITLY INSTRUCT THE HEADER ABOUT THE CONTENT TYPE. HERE - JSON
header('Content-type: application/json');
if($_POST["mode"]=="newuser"){
$gcmRegID = htmlspecialchars(trim($_POST["regID"]));
$gcmUserName = htmlspecialchars(trim($_POST["userName"]));
$gcmFolderName = htmlspecialchars(trim($_POST["folderName"]));
$gcmDate = date("d/m/y");
// I WOULD STRONGLY SUGGEST YOU USE PDO FOR YOUR DATABASE TRANSACTIONS:
// HERE'S HOW:
//DATABASE CONNECTION CONFIGURATION:
defined("HOST") or define("HOST", "localhost"); //REPLACE WITH YOUR DB-HOST
defined("DBASE") or define("DBASE", "database"); //REPLACE WITH YOUR DB NAME
defined("USER") or define("USER", "root"); //REPLACE WITH YOUR DB-USER
defined("PASS") or define("PASS", "root"); //REPLACE WITH YOUR DB-PASS
// ESTABLISH A CONNECTION AND DO YOUR WORK WITHIN A TRY-CATCH BLOCK...
try {
$dbh = new PDO('mysql:host='.HOST.';dbname='. DBASE,USER,PASS);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// HERE: ALL YOUR BUSINESS LOGIC...
$in_user = "user";
$in_password = "NULL";
$in_email = "NULL";
$in_phone = "NULL";
$in_dob = "NULL";
$in_role = "user";
$in_dateJoined = "0000-00-00";
$folderName = "NULL";
$insertSQL = "INSERT INTO user(`password`, `regid`, `name`, `email`, `phone`, `dob`, `role`, `datejoined`, `foldername`) ";
$insertSQL .= " VALUES(:inPassword, :gcmRegID, :gcmUserName, :inEmail, :inPhone, :inDOB, :inRole, :gcmDate, :folderName)";
$arrInsertData = array(
'inPassword' => $in_password,
'gcmRegID' => $gcmRegID,
'gcmUserName' => $gcmUserName,
'inEmail' => $in_email,
'inPhone' => $in_phone,
'inDOB' => $in_dob,
'inRole' => $in_role,
'gcmDate' => $gcmDate,
'folderName' => $folderName
);
// PREPARE THE INSERT QUERY:
$insertStmt = $dbh->prepare($insertSQL);
// INSERT THE NEW ROW:
$insertStmt->execute($arrInsertData);
// OBTAIN THE ID OF THE INSERTED ROW TO BE USED AS SUFFIX FOR YOUR USER FOLDER
$id = $dbh->lastInsertId();
// WHAT HAPPENS WHEN 2 USERS HAVE THE SAME USERNAME??? DID YOU THINK ABOUT THAT?
// TO CIRCUMVENT THIS ISSUE; I WOULD SUGGEST FIRST TO INSERT THE DATA TO THE DATABASE...
// THEN USE THE ID AS A SUFFIX TO MAKE EACH USER DIRECTORY UNIQUE & THAT IS THE APPROACH TAKEN HERE THOUGH...
// NOW YOU CAN CREATE YOUR FOLDER USING THIS ID: $id
// LIKE THIS; 2 USERS WITH USERNAME "android_user" CAN HAVE 2 DIFFERENT FOLDERS LIKE SO: "android_user_97" & "android_user_102"
$userDirectory = "./users/" . $gcmFolderName . "_" . $id;
mkdir($userDirectory);
// DID IT OCCUR TO YOU THAT 2 USERS MIGHT HAVE THE SAME USERNAME IN WHICH CASE MYSQL (INSTEAD OF YOU) HAS TO DECIDE WHICH USER TO UPDATE?
// THAT IS WHY DATABASE TABLES ARE DESIGNED TO HAVE UNIQUE IDENTIFIERS LIKE UUID OR ID OR UID OR ANY TOKEN TO MAKE EACH ROW UNIQUE...
// WE ARE ADOPTING THIS APPROACH IN THE UPDATE QUERY... THAT IS: WE UPDATE THE ROW USING THE ID ABOVE... ASSUMING THAT IS A UNIQUE COLUMN THOUGH.
$updateSQL = "UPDATE user SET foldername=:newDirName WHERE id=:ID";
// NOW UPDATE THE ROW TO TAKE INTO ACCOUNT THE UNIQUE USER-DIRECTORY (USING THE ID AS THE KEY)
$arrUpdateData = array(
'newDirName' => $userDirectory,
'ID' => $id // THIS ASSUMES THAT THE PRIMARY KEY OF YOUR TABLE IS CALLED id OTHERWISE USE THE APPROPRIATE KEY NAME: EG: reg_id OR WHATEVER
);
// PREPARE THE UPDATE QUERY:
$insertStmt = $dbh->prepare($updateSQL);
// UPDATE THE NEWLY CREATED ROW:
$insertStmt->execute($arrUpdateData);
// BUILD THE RESPONSE JSON DATA
$arrResponse = array(
'folderName' => $userDirectory,
'id' => $id,
);
// SEND THE RESPONSE AS JSON IF ALL WORKS FINE TILL HERE...
// THAT MEANS: SEND THE DATA IN $arrResponse AND TERMINATE THE SCRIPT - THE JOB IS DONE.
// NO NEED FOR ALL THOSE ECHO STATEMENTS AS THE YOU ARE EXPLICITLY SENDING BACK JSON DATA.
die( json_encode($arrResponse) );
}catch(PDOException $e){
// IF THERE WAS ANY KIND OF PDO ERROR, SEND IT BACK ANYWAYS - BUT ALSO AS JSON:
$arrResponse = array(
'error' => $e->getMessage()
);
die( json_encode($arrResponse) );
}
}
I can't test the code right now (sorry), but I think it should be something like this:
try {
RequestParams rParams = new RequestParams();
rParams.put("example", "example"); // POST
AsyncHttpClient client = new AsyncHttpClient();
client.get(pageURL, rParams, new JsonHttpResponseHandler() {
#Override
public void onSuccess(JSONArray jsonArray) {
super.onSuccess(jsonArray);
//process JSON Array
}
#Override
public void onFailure(Throwable throwable, JSONArray jsonArray) {
super.onFailure(throwable, jsonArray);
Log.d(TAG, "error", throwable);
}
});
} catch (Exception e) {
Log.d(TAG, "exception", e);
}
Otherwise I made a very light WebClient, you may want to give it a shot:
https://github.com/omaflak/WebClient
This is a short sample:
WebClient client = new WebClient();
client.setOnRequestListener(new OnRequestListener() {
#Override
public void onRequest(String response, int requestID) {
Log.e(TAG, response);
}
#Override
public void onError(int error_code, String message) {
Log.e(TAG, message);
}
});
Pair p = new Pair("field1", "value1");
Pair p2 = new Pair("field2", "value2");
client.requestAsync("http://your-api.com", WebClient.POST, Arrays.asList(p, p2), 1);
// requestAsync(String url, String method, List<Pair<String, String>> postData, int requestID)
To use it, simply add to your dependencies:
compile 'me.aflak.libraries:webclient:1.0'
Before listing out the items, I have a function of the app to create a new data where it includes a unique id from another activity. The unique data is "sid". I used PHP to connect to a phpmyadmin database.
<?php
// array for JSON response
$response = array();
// check for required fields
if (isset($_POST['foodName']) && isset($_POST['foodPrice']) && isset($_POST['foodType']) && isset($_POST['sid']) {
$foodName = $_POST['foodName'];
$foodPrice = $_POST['foodPrice'];
$foodType = $_POST['foodType'];
$sid = $_POST['sid'];
// 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 food(foodName, foodPrice, foodType, sid) VALUES('$foodName', '$foodPrice', '$foodType', '$sid')");
// check if row inserted or not
if ($result) {
// successfully inserted into database
$response["success"] = 1;
$response["message"] = "Food 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);
}
?>
And this is the intent to receive the data from the other activity :
Intent i = getIntent();
// getting product id (sid) from intent
sid = i.getStringExtra(TAG_SID);
Lastly, I have the this in the class when it is executed :
protected String doInBackground(String... args) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("foodName", getFoodName));
params.add(new BasicNameValuePair("foodPrice", getFoodPrice));
params.add(new BasicNameValuePair("foodType", getFoodType));
params.add(new BasicNameValuePair("sid", sid));
Is there something that I did wrong somewhere? On my table I have this "sid" too.
you have to do the following
in the first Activity
Intent intent = new Intent(getBaseContext(), SignoutActivity.class);
intent.putExtra("sid", VALUE);
startActivity(intent);
in second activity
Bundle extras = getIntent().getExtras();
if (extras != null) {
String value = extras.getString("sid");
}
I've created an login activity on android, for that you need email address and password.
It working but since I'm new on android, I don't know how to fetch the rest of user information and save it in the sharedpreferences.
Please help me
login.php
<?php
//load and connect to MySQL database stuff
require("config.inc.php");
if (!empty($_POST)) {
//gets user's info based of a username.
$query = "
SELECT
user_id,
user_name,
user_email,
user_password,
user_salt,
user_mobile,
user_country
FROM users
WHERE
user_email = :email
";
$query_params = array(
':email' => $_POST['user_email']
);
try {
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
catch (PDOException $ex) {
// For testing, you could use a die and message.
//die("Failed to run query: " . $ex->getMessage());
//or just use this use this one to product JSON data:
$response["success"] = 0;
$response["message"] = "Database Error 1. Please Try Again!";
die(json_encode($response));
}
//This will be the variable to determine whether or not the user's information is correct.
//we initialize it as false.
$validated_info = false;
//fetching all the rows from the query
$row = $stmt->fetch();
if ($row) {
//if we encrypted the password, we would unencrypt it here, but in our case we just
//compare the two passwords
$check_password = hash('sha256', $_POST['user_password'] . $row['user_salt']);
for($round = 0; $round < 65536; $round++)
{
$check_password = hash('sha256', $check_password . $row['user_salt']);
}
if($check_password === $row['user_password'])
{
// If they do, then we flip this to true
$login_ok = true;
}
}
// If the user logged in successfully, then we send them to the private members-only page
// Otherwise, we display a login failed message and show the login form again
if ($login_ok) {
// Here I am preparing to store the $row array into the $_SESSION by
// removing the salt and password values from it. Although $_SESSION is
// stored on the server-side, there is no reason to store sensitive values
// in it unless you have to. Thus, it is best practice to remove these
// sensitive values first.
unset($row['user_password']);
unset($row['user_salt']);
// This stores the user's data into the session at the index 'user'.
// We will check this index on the private members-only page to determine whether
// or not the user is logged in. We can also use it to retrieve
// the user's details.
$_SESSION['user_email'] = $row;
$response["success"] = 1;
$response["message"] = "Login successful!";
die(json_encode($response));
} else {
// Show them their username again so all they have to do is enter a new
// password. The use of htmlentities prevents XSS attacks. You should
// always use htmlentities on user submitted values before displaying them
// to any users (including the user that submitted them). For more information:
// http://en.wikipedia.org/wiki/XSS_attack
$submitted_username = htmlentities($_POST['user_email'], ENT_QUOTES, 'UTF-8');
$response["success"] = 0;
$response["message"] = "Invalid Credentials!";
die(json_encode($response));
}
} else {
?>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Login</title>
</head>
<body>
<h1>Login</h1>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<p>
<label>Email:</label><br>
<input name="user_email" type="text" value="" maxlength="254"/>
</p>
<p>
<label>Password:</label><br>
<input name="user_password" type="password" value="" maxlength="16"/>
</p>
<p>
<input type="submit" value="Login" name="submit"/>
</p>
</form>
Register
</body>
</html>
<?php } ?>
LoginActivity.java
class AttemptLogin extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
*/
boolean failure = false;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(LoginActivity.this);
pDialog.setMessage(getString(R.string.em_AttemptingLogin));
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected String doInBackground(String... args) {
// TODO Auto-generated method stub
// Check for success tag
int success;
/*String user_name = "";*/
String user_email = etEmail.getText().toString();
String user_password = etPassword.getText().toString();
/* String user_mobile = "";
String user_country = "";*/
try {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("user_email", user_email));
params.add(new BasicNameValuePair("user_password", user_password));
Log.d("request!", "starting");
// getting product detail s by making HTTP request
JSONObject json = jsonParser.makeHttpRequest(
LOGIN_URL, "POST", params);
// check your log for json response
Log.d("Login attempt", json.toString());
// json success tag
success = json.getInt(TAG_SUCCESS);
if (success == 1) {
Log.d("Login Successful!", json.toString());
//SAVE
SharedPreferences ui = getSharedPreferences("UserInfo", MODE_PRIVATE);
SharedPreferences.Editor edUi = ui.edit();
/*edUi.putString("user_name", user_name);*/
edUi.putString("user_email", user_email);
/*edUi.putString("user_mobile", user_mobile);
edUi.putString("user_country", user_country);*/
edUi.commit();
startActivity(new Intent(LoginActivity.this, MainActivity.class));
finish();
// Returns Toast "Login success!"
//return json.getString(TAG_MESSAGE);
} else {
Log.d("Login Failure!", json.getString(TAG_MESSAGE));
return json.getString(TAG_MESSAGE);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* *
*/
protected void onPostExecute(String file_url) {
// dismiss the dialog once product deleted
pDialog.dismiss();
if (file_url != null) {
Toast.makeText(LoginActivity.this, file_url, Toast.LENGTH_LONG).show();
}
}
}
I've tried the same way that email but don't work, you can see it's commented /* */ on .java
Thanks
Server side
My PHP is rather rusty but I am pretty sure that if you simply echo your json parsed result, then that information is capturen in the JSONObject on your android:
echo json_encode($response);
Cracking up the JSONObject
On your android you should then hopefully have every piece of information from the $result object available.
To pull out that information do something like (unrelated example just to show the mechanics):
JSONObject jsonObject; // ... retreived earlier in the code
try {
if (jsonObject.getString("status").equals("OK")) {
jsonObject = jsonObject.getJSONArray("results")
.getJSONObject(0);
jsonObject = jsonObject.getJSONObject("geometry");
jsonObject = jsonObject.getJSONObject("location");
String lat = jsonObject.getString("lat");
String lng = jsonObject.getString("lng");
position = new LatLng(Double.valueOf(lat),
Double.valueOf(lng));
}
} catch (JSONException e) {
Log.e(TAG, e.getMessage(), e);
}
Suggestion regarding shared preferences
Example saving string in shared preferences and retrieve it again anywhere in your app.
public class PreferencesData {
public static void saveString(Context context, String key, String value) {
SharedPreferences sharedPrefs = PreferenceManager
.getDefaultSharedPreferences(context);
sharedPrefs.edit().putString(key, value).commit();
}
public static String getString(Context context, String key, String defaultValue) {
SharedPreferences sharedPrefs = PreferenceManager
.getDefaultSharedPreferences(context);
return sharedPrefs.getString(key, defaultValue);
}
}
Usage:
// save a note to the 'mynote' key
PreferencesData.saveString(context, "mynote", "This is a test note");
// retrieve the 'This is a test note' String
String note = PreferencesData.getString(context, "mynote", "");
Optional note:
I prefer to have as few hard coded strings as possible, so I have a /res/values/strings_prefkeys.xml file that I use to store preference keys. For the note example this file would contain:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="key_note">key_note</string>
</resources>
And the above save and retrieval would then become:
// save a note to the 'mynote' key
PreferencesData.saveString(context, context.getString(R.string.key_note), "This is a test note");
// retrieve the 'This is a test note' String
String note = PreferencesData.getString(context, context.getString(R.string.key_note), "");
This is simply a matter of organisation and minimizing the risk of accidental duplicate keys that would yield some hard to track down bugs.
I've managed to fetch user information with this easy way after a long time of tweaking:
Login.php
$query = "SELECT * FROM users WHERE user_email = :email";
and
$response["success"] = 1;
$response["message"] = "Sessão iniciada com sucesso!";
$response["user_name"] = $row['user_name'];
$response["user_mobile"] = $row['user_mobile'];
$response["user_country"] = $row['user_country'];
// echoing JSON response
echo json_encode($response);
//die(json_encode($response));
on LoginActivity.java doInBackground
String user_name = "";
String user_email = etEmail.getText().toString();
String user_password = etPassword.getText().toString();
String user_mobile = "";
String user_country = "";
if success
user_name = json.getString("user_name");
user_mobile = json.getString("user_mobile");
user_country = json.getString("user_country");
//SAVE
SharedPreferences ui = getSharedPreferences("UserInfo", MODE_PRIVATE);
SharedPreferences.Editor edUi = ui.edit();
edUi.putString("user_name", user_name);
edUi.putString("user_email", user_email);
edUi.putString("user_mobile", user_mobile);
edUi.putString("user_country", user_country);
edUi.commit();
This was the "easy" way I've found, I know it's not the best but it works just fine! :)
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