I am in a problem can any one help me please.
I have a php file which i am calling from my java class file's Asynctask.
In the Asynctask i am sending three variables email,password and pin.
What is happening, is that when i run my php with hardcoded values it gives me proper result.
RESULT IS:
Inside 1st if
Inside 2nd if
Verified
main if
But wen i try running my php through the code it gives me wrong result
RESULT IS:
Inside 1st if
Invalid
main if
I'am not able to understand why is this happening please Guide me.
My PHP File
<?php
require 'DbConnect.php';
$i=1;
$Password = $_POST["password"];
$Email = $_POST["email"];
$Pin = $_POST["pin"];
//$KeyCode = $_REQUEST["key"];
if((isset($_POST["password"])) && (isset($_POST["email"])) && (isset($_POST["pin"])))
{
$query4 = ("SELECT seller_id, name, email, password, verification_Pin, verification_Code, created_Date FROM `seller` WHERE email = '$Email'");
$query_run = mysql_query($query4);
$row=mysql_fetch_row($query_run);
$int=$row[0];
$strName=$row[1];
$strEmail=$row[2];
$strPwd=$row[3];
$strPin=$row[4];
echo $Pin;
echo $Password;
echo $Email;
echo $int;
echo $strEmail;
echo $strPwd;
echo $strPin;
if(($Email==$strEmail) && ($Password==$strPwd) && ($Pin==$strPin))
{
global $i;
$i=2;
$id=updateValidation($int);
echo $id;
if($id==1)
{
echo "Verified";
}
else
{
echo "Not Verified";
}
}
else
{
echo "Invaild";
}
}
else
{
echo "Values not set";
}
function updateValidation($sid)
{
global $i;
if($i==2)
{
echo "Inside Update vAlidation";
$queryUpdate = ("UPDATE `seller` SET verification_Pin = 0, verification_Code = 'Verified', created_Date = CURDATE() where seller_id='$sid'");
if(mysql_query($queryUpdate))
{
return 1;
}
else
{
return 2;
}
}
else
{
echo "i not 2";
}
}
?>
My Class file:
Button ok = (Button) myDialog
.findViewById(R.id.button1);
et_pin = (EditText) myDialog
.findViewById(R.id.editText1);
ok.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Toast.makeText(getApplicationContext(),
"CLICKED OK", Toast.LENGTH_LONG).show();
pin = et_pin.getText().toString();
Toast.makeText(
getApplicationContext(),
"email,pass,pin= " + str1 + "," + str2
+ "," + pin, Toast.LENGTH_LONG)
.show();
new App_pin_Task().execute(FILENAME_pin);
// Intent intent = new
// Intent(Dealer_details.this,
// Login.class);
// startActivity(intent);
}
});
public class App_pin_Task extends AsyncTask<String, Integer, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#SuppressLint("NewApi")
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
Toast.makeText(getApplicationContext(),
"Inside App_pin_Task post Execute(Result)=" + result,
Toast.LENGTH_LONG).show();
if (result.contains("Invalid")) {
et_pin.setText("");
} else {
Intent myIntent = new Intent(Login.this, UserActivity.class);
startActivity(myIntent);
}
}
#Override
protected void onProgressUpdate(Integer... values) {
// TODO Auto-generated method stub
super.onProgressUpdate(values);
}
#Override
protected String doInBackground(String... params) {
// String is = null;
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(
"http://animsinc.com/verifyEmail.php");
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(
4);
nameValuePairs.add(new BasicNameValuePair("email", str1));
nameValuePairs.add(new BasicNameValuePair("password", str2));
nameValuePairs.add(new BasicNameValuePair("pin", pin));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
httpclient.execute(httppost);
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = EntityUtils.toString(entity);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
}
return is;
}
}
What is being returned with
$Password = $_REQUEST["password"];
$Email = $_REQUEST["email"];
$Pin = $_REQUEST["pin"];
$KeyCode = $_REQUEST["key"];
Your server configuration may have this option disabled and not returning anything.
You shouldn't use $_REQUEST anyway because you can never be sure where the data is actually coming from: $_POST, $_GET or $_cookie.
try this!
Change this
$Password = $_REQUEST["password"];
$Email = $_REQUEST["email"];
$Pin = $_REQUEST["pin"];
$KeyCode = $_REQUEST["key"];
to for Get Request
$Password = $_GET["password"];
$Email = $_GET["email"];
$Pin = $_GET["pin"];
$KeyCode = $_GET["key"];
or for Post Request
$Password = $_POST["password"];
$Email = $_POST["email"];
$Pin = $_POST["pin"];
$KeyCode = $_POST["key"];
or
"SELECT seller_id, name, email, password, verification_Pin,
verification_Code, created_Date FROM seller WHERE email = '".$Email."'"
Complementing the answer from fayeq-ali-khan I would also do the following;
First use post and add html special character for security.
htmlspecialchars => Convert special characters to HTML entities
$Password = htmlspecialchars($_POST['password'],ENT_QUOTES);
$Email = htmlspecialchars($_POST['email'],ENT_QUOTES);
$Pin = htmlspecialchars($_POST['pin'],ENT_QUOTES);
$KeyCode = htmlspecialchars($_POST['key'],ENT_QUOTES);
Also on your android activity and before you send the string it would be a good idea to trim the value to make sure that you are not transmitting empty character that can also mess up with the PHP
nameValuePairs.add(new BasicNameValuePair("email", str1.trim()));
nameValuePairs.add(new BasicNameValuePair("password", str2.trim()));
nameValuePairs.add(new BasicNameValuePair("pin", pin.trim()));
I hope it help you with something
Related
I need help.
Have seen similar questions but I cant still do it. So I post mine.
php codes runs well so far. Ijust dont know how to get the array.
How can I get the array from php and list it in my alertdialog like this:
soy sauce - $1
onion - $1
total= $2
Or is this possible or not? Or maybe please tell me what to add in here.
Thanks for your time in advance. Any form of help would be appreciated.
This are my codes:
public class updateData2 extends AsyncTask<String, String, String> {
#Override
protected String doInBackground(String... params) {
ArrayList<NameValuePair> postVars = new ArrayList<>();
postVars.add(new BasicNameValuePair("JSON", String.valueOf(EverythingJSON)));
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://abcabc.com/buy_now.php");
try {
httppost.setEntity(new UrlEncodedFormEntity(postVars));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
try {
HttpResponse response = httpclient.execute(httppost);
String responseBody = EntityUtils.toString(response.getEntity());
} catch (ClientProtocolException e) {
e.printStackTrace();
Log.v("MAD", "Error sending... ");
} catch (IOException e) {
e.printStackTrace();
Log.v("MAD", "Error sending... ");
}
return null;
}
#Override
protected void onPostExecute(String result) {
Toast.makeText(Cart.this,EverythingJSON.toString(), Toast.LENGTH_LONG).show();
AlertDialog.Builder builder = new AlertDialog.Builder(Cart.this);
builder.setTitle("ORDER:");
builder.setMessage(EverythingJSON.toString());
builder.setPositiveButton("Confirm",
new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int id)
{
}
});
builder.show();
}
}
php
<?php
require "conn.php";
$total = 0;
// $ing = array("ampalaya", "soy sauce");
$JSON_Received = $_POST["JSON"];
$obj = json_decode($JSON_Received, true);
$products_name_array = array();
$products_price_array = array();
// foreach($ing as $value){
foreach($obj['ques'] as $value){
$sql="select MIN(product_price) , product_id , store_id , product_name,product_unit_of_measure , product_price ,product_stock from products where product_name like '%$value%'";
$result2 = mysqli_query($conn, $sql);
if(mysqli_num_rows($result2) > 0){
while($row = mysqli_fetch_assoc($result2)){
$product_id=$row['product_id'];
$store_id=$row['store_id'];
$product_name=$row['product_name']; $products_name_array[] = $product_name;
$product_unit_of_measure=$row['product_unit_of_measure'];
$product_price=$row['product_price']; $products_price_array[] = $product_price;
$total = $total+$product_price;
}}
}
foreach($products_name_array as $key => $value) {
echo $products_name_array[$key] . " - " . "$" . $products_price_array[$key] . ".00" ."<br>";
}
echo "</br>";
echo "</br>";
echo "TOTAL IS: ".$total. ".00";
?>
example:
getArray.php
<? echo json_encode($your_array);?>
and in android use for example retrofit library(http client)
interface phpApi{
#GET("url/getArray.php")
Call<YourObject> getArray();
}
I dont think I have anything deprecated in my code, when I run the PHP script I get the success, but nothing appears in the database.
Heres the PHP Code.
<?php include "../inc/dbinfo.inc"; ?>
<?php
$connect = new mysqli("DB_SERVER","DB_USERNAME","DB_PASSWORD","DB_DATABASE");
if(!$connect){
die('error');
}
else
{
echo "success";
}
$username = isset($_POST['username']) ? $_POST['username'] : '';
$password = isset($_POST['password']) ? $_POST['password'] : '';
$givenname = isset($_POST['givenname']) ? $_POST['givenname'] : '';
$email = isset($_POST['email']) ? $_POST['email'] : '';
$phonenumber = isset($_POST['phonenumber']) ? $_POST['phonenumber'] : '';
$sql = "INSERT INTO test(username,password,givenname,email,phonenumber) VALUES ('$username', '$password', '$givenname', '$email', '$phonenumber')";
mysqli_close($connect);
?>
Heres the Android Code.
private void insertToDatabase(){
class SendPostReqAsyncTask extends AsyncTask<String, Void,String >
#Override
protected String doInBackground(String... params) {
String paramUsername = params[0];
String paramPassword = params[1];
String paramGivenname = params[2];
String paramEmail = params[3];
String paramPhonenumber = params[4];
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("username", username.getText().toString()));
nameValuePairs.add(new BasicNameValuePair("password", password.getText().toString()));
nameValuePairs.add(new BasicNameValuePair("givenname", givenName.getText().toString()));
nameValuePairs.add(new BasicNameValuePair("email", email.getText().toString()));
nameValuePairs.add(new BasicNameValuePair("phonenumber", phone.getText().toString()));
try {
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(Constantss.DB_DNS);
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return "success";
}
#Override
protected void onPostExecute(String result){
super.onPostExecute(result);
Toast.makeText(getApplicationContext(),result,Toast.LENGTH_LONG).show();
}
}
SendPostReqAsyncTask sendPostReqAsyncTask = new SendPostReqAsyncTask();
// sendPostReqAsyncTask.execute(uname,pword, gname, lmail,pnumb);
}
I get the success from the Android Code to, but nothing appears in the database table.
Does anyone know the problem? Thanks!
You didn't execute the query.
So use:
mysqli_query($connect, $sql); and check for errors on it also.
References:
http://php.net/manual/en/mysqli.query.php
http://php.net/manual/en/mysqli.error.php
Since another answer was given and I have pointed that out in comments first, just so we set the record straight.
You're also open to an sql injection. Use a prepared statement:
https://en.wikipedia.org/wiki/Prepared_statement
You don't execute the query in your code. Also I would strongly suggest to sanitize the user input.
This asks for SQL injection. Consult: How can I prevent SQL injection in PHP?
Run the query:
$res = mysqli_query($connect, $sql);
I had search many things but didn't work. So this is my problem.
I have succeed to make login form with responseHandler. This is the code :
public void login()
{
httpClient=new DefaultHttpClient();
httpPost= new HttpPost("http://studentstracking.hol.es/loginDatabase2.php");
nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("username",txtId.getText().toString().trim()));
nameValuePairs.add(new BasicNameValuePair("password",txtPassword.getText().toString().trim()));
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
response=httpClient.execute(httpPost);
ResponseHandler<String> responseHandler = new BasicResponseHandler();
final String response = httpClient.execute(httpPost, responseHandler);
System.out.println("Response : " + response);
runOnUiThread(new Runnable() {
public void run() {
tv.setText("Response from PHP : " + response);
dialog.dismiss();
}
});
if(response.equalsIgnoreCase("User Found")){
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(LoginActivity.this,"Login Success", Toast.LENGTH_SHORT).show();
}
});
startActivity(new Intent(LoginActivity.this, student_activity.class));
}else{
showAlert();
}}
And this is the PHP code :
$username = $_POST['username'];
$password = $_POST['password'];
$query_search = "select * from user2 where kode_user2 = '".$username."' AND password = '".$password."'";
$query_exec = mysqli_query($conn, $query_search) or die(mysqli_error($conn));
$rows = mysqli_num_rows($query_exec);
if($rows == 0) {
echo "No Such User Found";
}
else {
echo "User Found";
}
But this time i want to execute the PHP and get the value from it and store it into variable or maybe store it into SQLite.
This is the PHP code :
$query_search1 = "SELECT `schedule`.`kode_schedule`,`schedule`.`kode_matkul`,`matakuliah`.`title`,`schedule`.`ruang`,`kelas`.`latitude`,`kelas`.`longitude`,`kelas`.`lantai`,`schedule`.`hari`,`schedule`.`jam` FROM schedule LEFT JOIN `u466318196_track`.`matakuliah` ON `schedule`.`kode_matkul` = `matakuliah`.`kode_matkul` LEFT JOIN `u466318196_track`.`kelas` ON `schedule`.`ruang` = `kelas`.`ruang` WHERE(( kode_schedule = 'sch0001'))";
$query_exec1 = mysqli_query($conn, $query_search1) or die(mysqli_error($conn));
while ($data2 = mysqli_fetch_assoc($query_exec1))
{
$response['length'][] = $data2;
}
print json_encode($response);
And the result of this json is :
{
"length":
[
{
"kode_schedule":"sch0001",
"kode_matkul":"TIB01",
"title":"Basis Data",
"ruang":"501",
"latitude":"-6.18861653446272",
"longitude":"106.801122526546",
"lantai":"5",
"hari":"Selasa",
"jam":"17:45:00"
},
{
"kode_schedule":"sch0001",
"kode_matkul":"TIB02",
"title":"Pemrograman Berorientasi Objek",
"ruang":"LABB",
"latitude":"-6.18864706134991",
"longitude":"106.801161122636",
"lantai":"5",
"hari":"Selasa",
"jam":"19:30:00"
}
]
}
So i want to store the "kode_schedule","kode_matkul",etc values into variable such as String or maybe string with arrays.
Please kindly help me.
You are getting results in response string.
JSONObject mainObject=new JSONObject(response);
for(int i: 0 and 1){
mainObject.getJSONArray("length").getJSONObject(i).getString("kode_schedule");
mainObject.getJSONArray("length").getJSONObject(i).getString("kode_matkul");
}
use json method to access accordingly. Their are are so many tutorial to learn json parsing.
I have My databases on an xampp server and my activity and php file is given below. The problem in this page is that when I run application it always throws an exception. It always shows my last message that there is "Some problem is there." My submission date is due soon.
This is my Activity file
public class AdminLoginActivity extends Activity {
TextView username, password, message;
Button SignIn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_admin_login);
StrictMode.enableDefaults();
username = (TextView) findViewById(R.id.adminusername);
password = (TextView) findViewById(R.id.adminpassword);
message = (TextView) findViewById(R.id.textView5);
SignIn = (Button) findViewById(R.id.adminloginbtn);
SignIn.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
checkAdminData();
}
});
}
public void checkAdminData()
{
InputStream isr = null;
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://localhost:1234/adminlogin.php");
try
{
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair> (2);
nameValuePairs.add(new BasicNameValuePair("username", username.getText().toString()));
nameValuePairs.add(new BasicNameValuePair("password", password.getText().toString()));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
isr = entity.getContent();
}
catch (ClientProtocolException e)
{
Log.e("log_tag", "Error in Http connection " + e.toString());
message.setText("couldn't connect to database");
}
catch (IOException e)
{
}
String responseText = null;
try
{
String res = isr.toString();
// res = res.replaceAll("\\s+", "");
if (res.equals("1")) {
Intent i = new Intent(this, AdminMainPage.class);
startActivity(i);
}
else{
message.setText("Username or Password incorrect");
}
}
catch (Exception e)
{
Log.e("log_tag", "Sorry!! Incorrect Username or Password " + e.toString());
message.setText("Some problem is there");
}
}
}
PHP file:
<?php
$hostname_localhost ="localhost";
$database_localhost ="sibuilder";
$username_localhost ="root";
$password_localhost ="";
$localhost = mysql_connect($hostname_localhost,$username_localhost,$password_localhost)
or
trigger_error(mysql_error(),E_USER_ERROR);
mysql_select_db($database_localhost, $localhost);
$username = $_POST['username'];
$password = $_POST['password'];
$query_search = "select * from login l, admin a where a.username = '".$username."' AND l.password = '".$password. "'";
$query_exec = mysql_query($query_search) or die(mysql_error());
$rows = mysql_num_rows($query_exec);
//echo $rows;
if($rows == 0) {
echo 0;
}
else {
echo 1;
}
?>
If you want to use your php script instead json format, can refer these questions
Android: AsyncTask to make an HTTP GET Request? Make an HTTP request with android to handle the response. Using AsyncTask is recommended.
I'm trying to update a row in my database via my android app. My pulling from the database is working but I'm having trouble with the updating. My code for updating is as follows:
My AsyncTask class:
private class UpdateAnimalTask extends AsyncTask<Void, Void, Boolean>
{
#Override
protected Boolean doInBackground(Void... arg0)
{
try
{
ID = (EditText) findViewById(R.id.eTid);
Name = (EditText) findViewById(R.id.eTname);
Type = (EditText) findViewById(R.id.eTtype);
Breed = (EditText) findViewById(R.id.eTbreed);
Gender = (EditText) findViewById(R.id.eTgender);
Injuries = (EditText) findViewById(R.id.eTinjuries);
Treat = (EditText) findViewById(R.id.eTtreat);
String nM = Name.getText().toString();
String tP = Type.getText().toString();
String bR = Breed.getText().toString();
String gE = Gender.getText().toString();
String iN = Injuries.getText().toString();
String tR = Treat.getText().toString();
ArrayList<NameValuePair> up = new ArrayList<NameValuePair>();
up.add(new BasicNameValuePair("name", nM));
up.add(new BasicNameValuePair("type", tP));
up.add(new BasicNameValuePair("breed", bR));
up.add(new BasicNameValuePair("gender", gE));
up.add(new BasicNameValuePair("injuries", iN));
up.add(new BasicNameValuePair("treatment", tR));
String phpLink = "http://select.garethprice.co.za/update.php?name=" + nM;
Log.e("Test", up.toString());
dbUpdate(up, phpLink);
Log.e("Test", up.toString());
}
catch(Exception e)
{
Log.e("log_tag", "Error in uploading " + e.toString());
Toast.makeText(getBaseContext(), "Error " + e.toString(), Toast.LENGTH_LONG).show();
return false;
}
return true;
}
#Override
protected void onPostExecute(Boolean result)
{
if(result)
{
Toast.makeText(getBaseContext(), "Successfully updated", Toast.LENGTH_LONG).show();
}
}
}
My dbUpdate method which is being called inside my asynctask class:
public void dbUpdate(ArrayList<NameValuePair> data, String phpL)
{
InputStream iS = null;
try
{
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(phpL);
httppost.setEntity(new UrlEncodedFormEntity(data));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
iS = entity.getContent();
}
catch(Exception e)
{
Log.e("log_tag", "Error in http connection " + e.toString());
Toast.makeText(getBaseContext(), "Error " + e.toString(), Toast.LENGTH_LONG).show();
}
}
My php:
<?php
include_once 'db.php';
$con=mysql_connect(DB_HOST, DB_USER, DB_PASSWORD)or die("cannot connect");
mysql_select_db(DB_DATABASE)or die("cannot select DB");
$nM = $_GET['name'];
$tP = $_POST['type'];
$bR = $_POST['breed'];
$gE = $_POST['gender'];
$iN = $_POST['injuries'];
$tR = $_POST['treatment'];
$sql = "UPDATE tbl_Animals SET animal_Type = '$tP', animal_Breed = '$bR', animal_Gender = '$gE', animal_Injuries = '$iN', animal_Treatments = '$tR' WHERE animal_Name = '$nM'";
echo "test: " . $nM . $tP . $bR . $gE . $iN . $tR;
mysql_query($sql,$con) or die("error: " . mysql_error());
mysql_close($con)
?>
Executing the asynctask in my update button:
public void Update(View v)
{
new UpdateAnimalTask().execute();
}
The android code is not breaking so I suspect it's something with the php because my toast pops up that says update successful in my onPostExecute.
Thank you in advance.