I am trying to query SQL database with IMEI variable from android device, the variable is received (verified with log.txt), however whenever I replace '00000000000000' (android virtual device IMEI) with '$androidIMEI' the results are not returned but if I explicitly use the IMEI and not the variable I receive data.
<?php
include 'config.php';
$con=mysql_connect("$servername", "$username", "$password")or die("cannot connect");
mysql_select_db("$dbname")or die("cannot select DB");
$androidIMEI = isset($_POST['IMEI']) ? $_POST['IMEI'] : '';
//$f = fopen("log.txt", "w");
//fwrite($f, print_r($androidIMEI, true));
//fclose($f);
$sql = "SELECT * from users WHERE Request = '0' AND IMEI = '000000000000000' ";
//$sql = "SELECT * from users WHERE Request = '0' AND IMEI = '$androidIMEI ' "; //not working
$result = mysql_query($sql);
$json = array();
if(mysql_num_rows($result)){
while($row=mysql_fetch_assoc($result)){
$json['users'][]=$row;
}
}
mysql_close($con);
echo json_encode($json);
?>
Update: (printing SQL to log file)
$sql = "SELECT * from users WHERE Request = '0' AND IMEI = '$androidIMEI'";
$result = mysql_query($sql);
$f = fopen("log.txt", "w");
fwrite($f, print_r($sql, true));
fclose($f);
Reading Log File:
SELECT * from users WHERE Request = '0' AND IMEI = '000000000000000'
AND THIS IS WHY I HAVE NO IDEA WHY IT IS NOT WORKING
Second Update:
This might be useful, code from android, how I'm sending my IMEI to PHP:
class loadData extends AsyncTask<String, Integer, String> {
private StringBuilder sb;
private ProgressDialog pr;
private HttpResponse req;
private InputStream is;
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#SuppressWarnings("deprecation")
#Override
protected String doInBackground(String... arg0) {
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("IMEI",IMEI));
System.out.println("IMEI: "+IMEI);
try
{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://mysite/myfile.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
InputStreamReader ireader = new InputStreamReader(is);
BufferedReader bf = new BufferedReader(ireader);
sb = new StringBuilder();
String line = null;
while ((line = bf.readLine()) != null) {
sb.append(line);
}
Log.e("pass 1", "connection success ");
}
catch(Exception e)
{
System.out.println("Error catch e");
}
return id;
}
Change
"SELECT * from users WHERE Request = '0' AND IMEI = '$androidIMEI ' " with "SELECT * from users WHERE Request = '0' AND IMEI = '".$androidIMEI."' ".
Also you are vulnerable for SQL injections. Do not use deprecated mysql_* functions and filter your input. More information at How can I prevent SQL injection in PHP?
There is a space after $androidIMEI in your query.
$sql = "SELECT * from users WHERE Request = '0' AND IMEI = '$androidIMEI ' ";
should be
$sql = "SELECT * from users WHERE Request = '0' AND IMEI = '$androidIMEI';";
Try this line
$sql = "SELECT * from users WHERE Request = '0' AND IMEI = '{$android}IMEI'";
I hope it will work.
Just note those curly braces.
Related
I am trying to send a string to php script using namevaluepair. But i couldn't receive it on the other side. Here is my code.
protected String doInBackground(String... args) {
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
nameValuePairs.add(new BasicNameValuePair("Username",code ));
Log.v("username", code);
DefaultHttpClient httpclient = new DefaultHttpClient(new BasicHttpParams());
HttpPost httppost = new HttpPost("http://192.168.42.21:8080/sellapp/menuitem.php");
// Depends on your web service
httppost.setHeader("Content-type", "application/json");
InputStream inputStream = null;
String result = null;
try {
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
inputStream = entity.getContent();
// json is UTF-8 by default
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
result = sb.toString();
} catch (Exception e) {
// Oops
}
finally {
try{if(inputStream != null)inputStream.close();}catch(Exception squish {}
}
return result;
}
Here i want to pass the value in the string code to my php script. my php script is
$con = mysqli_connect(HOST,USER,PASS,DB);
$cst_id=$_REQUEST['Username'];
// $cst_id= 'cus02';
$sql = "
select
cust_code, segment_type, cust_name, cust_address, cust_payment_type, cust_credit_limit, cust_cr_balance
from customer where cust_code='".$cst_id."'
";
$res = mysqli_query($con,$sql);
$result = array();
while($row = mysqli_fetch_array($res)){
array_push(
$result,
[
'cust_id'=>$row[0],
'cust_seg'=>$row[1],
'cust_name'=>$row[2],
'cust_type'=>$row[3],
'cust_ad'=>$row[4],
'cust_cr'=>$row[5],
'cust_bl'=>$row[6]
]
);
}
echo json_encode(array("result"=>$result));
mysqli_close($con);
When I am giving the value directly to the php it works. But through name/value pair it returns a null array as result.
Please help me to get an answer.I tried questions related to it. But didn't worked.
<?php
$con = mysqli_connect(HOST,USER,PASS,DB);
$cst_id = $_POST['Username']; // --------- not $_REQUEST['Username'];
// $cst_id= 'cus02';
$sql = "select cust_code,segment_type,cust_name,cust_address,cust_payment_type,cust_credit_limit,cust_cr_balance from customer where cust_code='".$cst_id."' ";
$res = mysqli_query($con,$sql);
$result = array();
while($row = mysqli_fetch_array($res)){
array_push($result,
['cust_id'=>$row[0],
'cust_seg'=>$row[1],
'cust_name'=>$row[2],
'cust_type'=>$row[3],
'cust_ad'=>$row[4],
'cust_cr'=>$row[5],
'cust_bl'=>$row[6]
]);
}
//echo json_encode(array("result"=>$result));
echo json_encode($result);
mysqli_close($con);
?>
I have an error as stated in the title when trying to read SQL and encode it back to android.
I have tried the following:
Verified the value of $androidIMEI by printing to log file, value is returned as expected.
Verified the output of $sql and the query is OK (including the $_POST['myIMEI_toString']) value from android.
Verified the value of $json array, 2 arrays are returned as the query returns 2 rows from SQL, OK.
Replacing
$androidIMEI = isset($_POST['myIMEI_toString']) ? $_POST['myIMEI_toString'] : '';
WITH
$androidIMEI = "000000000000000" //works fine but I want to get that programmatically.
Code:
Android (Send IMEI):
TelephonyManager mngr = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
myIMEI = mngr.getDeviceId();
myIMEI_toString = myIMEI.toString();
...............
protected String doInBackground(String... arg0) {
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("myIMEI_toString",myIMEI_toString));
try
{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://path_on_server/file.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
InputStreamReader ireader = new InputStreamReader(is);
BufferedReader bf = new BufferedReader(ireader);
sb = new StringBuilder();
String line = null;
while ((line = bf.readLine()) != null) {
sb.append(line);
}
Log.e("pass 1", "connection success ");
}
catch(Exception e)
{
System.out.println("Error catch");
}
return id;
}
Android (JSON):
try {
JSONObject jsonResponse = new JSONObject(jsonResult);
JSONArray jsonMainNode = jsonResponse.optJSONArray("myarray");
for (int i = 0; i < jsonMainNode.length(); i++) {
JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
name = jsonChildNode.getString("Request_Name");
number = jsonChildNode.getString("Request_Number");
username = jsonChildNode.getString("Request_Username");
status = jsonChildNode.getString("Status");
arrName.add(name);
arrNumber.add(number);
arrUsername.add(username);
arrStatus.add(status);
System.out.println("Name: "+name);
System.out.println("Number: "+number);
System.out.println("Username: "+username);
System.out.println("Status: "+status);
}
} catch (JSONException e) {
Log.i("Error Log: ", e.toString());
System.out.println("Error: "+e.toString());
Toast.makeText(getApplicationContext(), "Error" + e.toString(), Toast.LENGTH_SHORT).show();
}
PHP:
<?php
include 'config.php';
//$androidIMEI = "000000000000000";
$androidIMEI = isset($_POST['myIMEI_toString']) ? $_POST['myIMEI_toString'] : '';
//$f = fopen("log.txt", "w");
//fwrite($f, print_r($androidIMEI, true));
//fclose($f);
$con=mysql_connect("$servername", "$username", "$password")or die("cannot connect");
mysql_select_db("$dbname")or die("cannot select DB");
$sql = "SELECT * from users WHERE Request='0' AND IMEI = '$androidIMEI' ";
$result = mysql_query($sql);
$json = array();
if(mysql_num_rows($result)){
while($row=mysql_fetch_assoc($result)){
$json['myarray'][]=$row;
}
}
else
{
//$error = "Error selecting record: " . $conn->error " ";
//$f = fopen("$error.txt", "w");
//fwrite($f, print_r($error, true));
//fclose($f);
}
$f = fopen("log.txt", "w");
fwrite($f, print_r($sql, true));
fclose($f);
mysql_close($con);
echo json_encode($json);
?>
Logcat Error:
org.json.JSONException: Value [] of type org.json.JSONarray cannot be converted to JSONObject
(i have asked this question before but will try again with more information)
i want to send all contacts with contact name and number in one row in one array in my android application like
john => "+92312xxxxxxx" ,
Right now i'm using namevaluepairs to post two arrays but it's not working like :
public class ContactList extends Activity {
public TextView outputText;
String phoneNumber = null;
String names = null;
String[] keyValue;
String[] kes;
int Count;
String s = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_contact_list);
outputText = (TextView) findViewById(R.id.textView1);
fetchContacts();
//Http connection
InputStream is=null;
List<NameValuePair> nameValuePairs =new ArrayList<NameValuePair>(1);
for (int i = 0; i < Count ; i++)
{
nameValuePairs.add(new BasicNameValuePair("CN[]", keyValue[i]));
nameValuePairs.add(new BasicNameValuePair("names[]",kes[i]));
Log.i("Response", "you sent :" +kes[i]+" :"+ keyValue[i] + "\n ");
}
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://192.168.1.107/older/ContactList.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
}
catch(ClientProtocolException e)
{
Log.e("ClientProtocol","Log_tag");
e.printStackTrace();
System.out.println("Excep: "+e);
}
catch(IOException e)
{
Log.e("Log_tag","IOException");
e.printStackTrace();
}
String result = "";
try
{
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
reader.close();
is.close();
result=sb.toString();
Log.i("Response", "result "+ result);
}
catch(Exception e)
{
Log.e("log_tag", "Error converting result "+e.toString());
}
//result = "[{\"0\":\"Muhaimin\",\"1\":\"3\",\"2\":\"o+\"}]";
try
{
JSONArray jArray = new JSONArray(result);
for (int i = 0; i < jArray.length(); i++)
{
s= s +";"+ jArray.getString(i) + "\n";
}
}
catch (Exception e)
{
Log.e("Response", "error fetching indexes" + e);
}
String[] friends= s.split(";");
StringBuffer output = new StringBuffer();
for (int i = 0; i < friends.length; i++)
{
Log.i("List","Your friends namee"+friends[i]);
output.append("\n Your friend's number"+ friends[i]);
}
}
//Fetch Contacts
public void fetchContacts() {
// String email = null;
Uri CONTENT_URI = ContactsContract.Contacts.CONTENT_URI;
String _ID = ContactsContract.Contacts._ID;
String DISPLAY_NAME = ContactsContract.Contacts.DISPLAY_NAME;
String HAS_PHONE_NUMBER = ContactsContract.Contacts.HAS_PHONE_NUMBER;
Uri PhoneCONTENT_URI = ContactsContract.CommonDataKinds.Phone.CONTENT_URI;
String Phone_CONTACT_ID = ContactsContract.CommonDataKinds.Phone.CONTACT_ID;
String NUMBER = ContactsContract.CommonDataKinds.Phone.NUMBER;
// Uri EmailCONTENT_URI = ContactsContract.CommonDataKinds.Email.CONTENT_URI;
//String EmailCONTACT_ID = ContactsContract.CommonDataKinds.Email.CONTACT_ID;
// String DATA = ContactsContract.CommonDataKinds.Email.DATA;
ContentResolver contentResolver = getContentResolver();
Cursor cursor = contentResolver.query(CONTENT_URI, null,null, null, null);
// Loop for every contact in the phone
Count = cursor.getCount();
if (cursor.getCount() > 0) {
keyValue= new String[Count];
kes= new String[Count];
while (cursor.moveToNext()) {
String contact_id = cursor.getString(cursor.getColumnIndex( _ID ));
String name = cursor.getString(cursor.getColumnIndex( DISPLAY_NAME ));
int hasPhoneNumber = Integer.parseInt(cursor.getString(cursor.getColumnIndex( HAS_PHONE_NUMBER )));
if (hasPhoneNumber > 0) {
// Query and loop for every phone number of the contact
Cursor phoneCursor = contentResolver.query(PhoneCONTENT_URI, null, Phone_CONTACT_ID + " = ?", new String[] { contact_id }, null);
while (phoneCursor.moveToNext())
{
int i=0;
String stu = phoneCursor.getString(phoneCursor.getColumnIndex(NUMBER));
phoneNumber +=":"+ stu;
names +=":" + name;
Log.i("List",stu + name +"\n" );
}
phoneCursor.close();
}
}
}
keyValue = phoneNumber.split(":");
kes = names.split(":");
Log.i("List","24th"+keyValue[23]);
Toast.makeText(getApplicationContext(), "99th "+keyValue[909] ,Toast.LENGTH_LONG).show();
}
PHP after receiving contacts will match them and return only those which have a match with database contacts. And then it returns contacts with names
i'm stuck with sending and receving part
Here is php code
<?php
define('DB_HOST', 'localhost');
define('DB_NAME', 'verification');
define('DB_USER','root');
define('DB_PASSWORD','');
// 1. Create a database connection
$connection = mysqli_connect(DB_HOST,DB_USER,DB_PASSWORD);
if (!$connection) {
die("Database connection failed: " . mysqli_error());
}
// 2. Select a database to use
$db_select = mysqli_select_db($connection, DB_NAME);
if (!$db_select) {
die("Database selection failed: " . mysqli_error());
}
$PhoneNum= $_POST["CN"];
$i=0;
$j=0;
$friends = array();
$Invite = array();
unset ($PhoneNum[0]);
foreach ($PhoneNum as $i=> $element){
//or do whatever you need to do to that variable
$query="SELECT Number FROM `user` WHERE Number=$element";
$query_exec = mysqli_query($connection ,$query);
if (!$query_exec)
{ echo mysql_error(); }
ELSE {
if(mysqli_num_rows($query_exec)>0)
{
$friends["$j"]= $PhoneNum[$i];
$j++;
}
else
{
;
}}
}
echo (json_encode($friends));
?>
You'll get a URL now that would look like:
www.example.com/yourscript?CN[]=keyValue1&names[]=key1&CN[]=keyValue2&names[]=key2 etc.. going on untill your whole list has looped.
I doubt that is what your PHP script wants to receive, you probably want to send the POST for each time you increment the loop. But thats just conjecture untill you post more information/code.
Instead send a JSON array as the value of the nameValuePair and convert it to a PHP array using json_decode function in the server side.
I am trying to make a HttpPost from my app to a php script, which will then insert data to a remote database. I'm not getting any runtime errors, but the data never gets inserted into my remote database.
Code:
public class InsertResult extends AsyncTask<String, String, String>
{
#Override
protected String doInBackground(String... arg0)
{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.<myDomain>.co.za/insertTeamResultwithCode.php");
try
{
ArrayList<NameValuePair> nameValues = new ArrayList<NameValuePair>(10);
nameValues.add(new BasicNameValuePair("Code", password));
nameValues.add(new BasicNameValuePair("Section", section));
nameValues.add(new BasicNameValuePair("Gender", gender));
nameValues.add(new BasicNameValuePair("WinningTeam", newResult.getWinningTeam()));
nameValues.add(new BasicNameValuePair("LosingTeam", newResult.getLosingTeam()));
nameValues.add(new BasicNameValuePair("FixtureD", newResult.getDate()));
nameValues.add(new BasicNameValuePair("FixtureT", newResult.getTime()));
nameValues.add(new BasicNameValuePair("Venue", newResult.getVenue()));
nameValues.add(new BasicNameValuePair("Court", newResult.getCourt()));
nameValues.add(new BasicNameValuePair("Texts", newResult.getText()));
httppost.setEntity(new UrlEncodedFormEntity(nameValues));
HttpResponse response = httpclient.execute(httppost);
}
catch (ClientProtocolException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result)
{
GoToJarvisDashboard();
}
}
And PhP script:
<?php
//Code verifications
$Code = $_GET['Code'];
//Variables for SQL INSERT
$Section = $_GET['Section'];
$Gender = $_GET['Gender'];
$WinningTeam = $_GET['WinningTeam'];
$LosingTeam = $_GET['LosingTeam'];
$FixtureD = $_GET['FixtureD'];
$FixtureT = $_GET['FixtureT'];
$Venue = $_GET['Venue'];
$Court = $_GET['Court'];
$Texts = $_GET['Texts'];
$SetsWon = $_GET['SetsWon'];
$SetsLost = $_GET['SetsLost'];
$Winner_Score = $_GET['Winner_Score'];
$Loser_Score = $_GET['Loser_Score'];
$dbname = '<dbName>';
$dbuser = '<user>';
$dbpass = '<password>';
$dbhost = '<host>t';
$connect = mysqli_connect($dbhost, $dbuser, $dbpass, $dbname) or die ("Unable to Connect to '$dbhost'");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$SQL = "SELECT * FROM squasdlw_db1.validationCodes WHERE Code = '$Code'";
$codeValid = mysqli_query($connect, $SQL) or die (mysqli_error($connect));
$response["no"] = array();
if (mysqli_num_rows($codeValid) > 0)
{
echo "Code is valid\n\n";
//Insert Result
$query = "INSERT INTO squasdlw_db1.jarvisTeamResults (Section,Gender,WinningTeam,LosingTeam,FixtureD,FixtureT,Venue,Court,Texts,SetsWon,SetsLost,Winner_Score,Loser_Score) VALUES('$Section','$Gender','$WinningTeam','$LosingTeam','$FixtureD','$FixtureT','$Venue','$Court','$Texts','$SetsWon','$SetsLost','$Winner_Score','$Loser_Score')";
$result = mysqli_query($connect, $query) or die (mysqli_error($connect));
echo "Result successfully submitted to Jarvis Remote Database: Table -> jarvisTeamResults\n\n" ;
//Update Winner on jarvisLogs
$query = "UPDATE squasdlw_db1.jarvisLogs SET Points = Points + '$Winner_Score', Played = Played + 1, Won = Won + 1 WHERE Gender = '$Gender' AND Section = '$Section' AND Team = '$WinningTeam'";
$result = mysqli_query($connect, $query) or die (mysqli_error($connect));
echo "Log update for '$WinningTeam': Table -> jarvisLogs\n\n";
//Update Winner on jarvisLogs
$query = "UPDATE squasdlw_db1.jarvisLogs SET Points = Points + '$Loser_Score', Played = Played + 1, Lost = Lost + 1 WHERE Gender = '$Gender' AND Section = '$Section' AND Team = '$LosingTeam'";
$result = mysqli_query($connect, $query) or die (mysqli_error($connect));
echo "Log update for '$LosingTeam': Table -> jarvisLogs\n\n";
$response["isValid"] = true;
echo json_encode($response);
}
else
{
$response["isValid"] = false;
echo "The code is not valid\n";
echo json_encode($response);
}
mysqli_close($connect);
?>
Whats even weirder is that if I try this in a web browser, it works fine and the data does get added to the remote database-
http://www.<myDomain>.co.za/insertTeamResultwithCode.php?Code=<password>&Section=A&Gender=Men&WinningTeam=NW&LosingTeam=KZN&FixtureD=2015-05-25&FixtureT=09:00:00&Venue=Puk&Court=6&Texts=Andrew%20(NW)%20beat%20Kevin%20(WP)%203-1&SetsWon=15&SetsLost=5&Winner_Score=15&Loser_Score=5
Please help out, I have no idea what is going wrong because it does not create runtime errors? I am about to go crazy...
You are doing an HttpPost so you should get your data via POST and not GET
//Code verifications
$Code = $_POST['Code'];
//Variables for SQL INSERT
$Section = $_POST['Section'];
$Gender = $_POST['Gender'];
$WinningTeam = $_POST['WinningTeam'];
$LosingTeam = $_POST['LosingTeam'];
$FixtureD = $_POST['FixtureD'];
$FixtureT = $_POST['FixtureT'];
$Venue = $_POST['Venue'];
$Court = $_POST['Court'];
$Texts = $_POST['Texts'];
$SetsWon = $_POST['SetsWon'];
$SetsLost = $_POST['SetsLost'];
$Winner_Score = $_POST['Winner_Score'];
$Loser_Score = $_POST['Loser_Score'];
Or change your android code to make GET requests :
HttpGet httpget = new HttpGet("http://www.example.com/insertTeamResultwithCode.php");
You are sending POST in android BUT you are expecting GET in php which are not the same.
Change the $_GET to $_POST and it will work.
Here a post that will tell you difference between then
Here another with some more details
my codes is fine, not returning any errors but the values being retrieved are the same as the previous field..for example, if i set table3 to 'HELLO' then table4 is also 'HELLO' which is kinda wrong,i wanted separate values..here is my code...
my SigninActivity:
public class SigninActivity extends AsyncTask<String,Void,String>{
private TextView statusField,roleField, sampleField;
private Context context;
private int byGetOrPost = 0;
//flag 0 means get and 1 means post.(By default it is get.)
public SigninActivity(Context context,TextView statusField,TextView roleField,TextView sampleField,int flag) {
this.context = context;
this.statusField = statusField;
this.roleField = roleField;
this.sampleField = sampleField;
byGetOrPost = flag;
}
protected void onPreExecute(){
}
#Override
protected String doInBackground(String... arg0) {
if(byGetOrPost == 0){ //means by Get Method
try{
String username = (String)arg0[0];
String password = (String)arg0[1];
String link = "http://XXX.XXX.X.X/XXX/ins.php?username="
+username+"&password="+password;
URL url = new URL(link);
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet();
request.setURI(new URI(link));
HttpResponse response = client.execute(request);
BufferedReader in = new BufferedReader
(new InputStreamReader(response.getEntity().getContent()));
StringBuffer sb = new StringBuffer("");
String line="";
while ((line = in.readLine()) != null) {
sb.append(line);
break;
}
in.close();
return sb.toString();
}catch(Exception e){
return new String("Exception: " + e.getMessage());
}
}
else{
try{
String username = (String)arg0[0];
String password = (String)arg0[1];
String link="http://XXX.XXX.X.X/XXX/sel.php";
String data = URLEncoder.encode("username", "UTF-8")
+ "=" + URLEncoder.encode(username, "UTF-8");
data += "&" + URLEncoder.encode("password", "UTF-8")
+ "=" + URLEncoder.encode(password, "UTF-8");
URL url = new URL(link);
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter
(conn.getOutputStream());
wr.write( data );
wr.flush();
BufferedReader reader = new BufferedReader
(new InputStreamReader(conn.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = null;
// Read Server Response
while((line = reader.readLine()) != null)
{
sb.append(line);
break;
}
return sb.toString();
}catch(Exception e){
return new String("Exception: " + e.getMessage());
}
}
}
#Override
protected void onPostExecute(String result){
this.statusField.setText("Login Successful");
this.roleField.setText(result);
this.sampleField.setText(result);
}
}
my select.php file (sel.php):
<?php
$con=mysqli_connect("localhost","root","","db_name");
if (mysqli_connect_errno($con))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$username = $_POST['username'];
$password = $_POST['password'];
$result = mysqli_query($con,"SELECT role,sample FROM table1 WHERE
username='$username' and password='$password'");
$row = mysqli_fetch_array($result);
$data = $row[0];
if($data){
echo $data;
}
mysqli_close($con);
?>
This is where your problem is:
#Override
protected void onPostExecute(String result){
this.statusField.setText("Login Successful");
this.roleField.setText(result);
this.sampleField.setText(result);
}
If you want different values for sampleField and roleField, you should set different values.
Update
I see where your other problem is. In the un-updated PHP source, you are selecting both role and sample from the database table, but you are outputting only role because $data equals $row[0]. If you want sample as well, you would need to retrieve $row[1] as well.
Or you could also use $row["role"] and $row["sample"] to get the values returned from the database table.
<?php
$con=mysqli_connect("localhost","root","","db_name");
if (mysqli_connect_errno($con))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$username = $_POST['username'];
$password = $_POST['password'];
$result = mysqli_query($con,"SELECT role,sample FROM table1 WHERE
username='$username' and password='$password'");
$row = mysqli_fetch_array($result);
if($row){
// returns a json object in the form
// {"role":"<role-from-database>","sample":"<sample-from-database>"}
$output = array("role" => $row["role"] ,"sample" => $row["sample"]);
echo json_encode($output);
}
mysqli_close($con);
?>
With the updated PHP source, you should process the JSON object in your SigninActivity.
Update 2
#Override
protected void onPostExecute(String result){
String role = "", sample = "";
// read the json object with JsonReader
JsonReader reader = new JsonReader(new StringReader(result));
reader.beginObject();
while (reader.hasNext()) {
String name = reader.nextName();
if (name.equals("role")) {
role = reader.nextString();
} else if (name.equals("sample")) {
sample = reader.nextString();
} else {
reader.skipValue();
}
}
reader.endObject();
// set the text here
}
Let me know if this helps.