Connecting Android to MySQL - php

So I'm really new to this. I was following a tutorial on web that showed how to connect these two. But everything I do it just jumps to catch part and it says "No connection". What am I missing? I also connect to a http server to use a PHP script which queries username and password from the database.
try
{
nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("username", username));
nameValuePairs.add(new BasicNameValuePair("password", password));
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
response = httpClient.execute(httpPost);
if(response.getStatusLine().getStatusCode()==200)
{
entity = response.getEntity();
if(entity != null)
{
InputStream instream = entity.getContent();
JSONObject jsonResponse = new JSONObject(instream.toString());
String retUser = jsonResponse.getString("upime");
String retPass = jsonResponse.getString("geslo");
if(username.equals(retUser) && password.equals(retPass))
{
SharedPreferences sp = getSharedPreferences("logindetails", 0);
SharedPreferences.Editor spedit = sp.edit();
spedit.putString("upime", username);
spedit.putString("geslo", password);
spedit.commit();
Toast.makeText(getBaseContext(), "Login successful", Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(getBaseContext(), "Failed to login", Toast.LENGTH_SHORT).show();
}
}
}
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(getBaseContext(), "No connection", Toast.LENGTH_LONG).show();
}

<?php
header('Content-Type: application/json');
$dbhost ="localhost";
$dbuser = "username";
$dbpass = "password";
$dbdb = "db";
$connect = mysql_connect($db_host, $dbuser, $dbpass) or die("connection error");
mysql_select_db($dbdb);
$username =$_POST['username'];
$password=$_POST['password'];
$query = mysql_query("SELECT * FROM users WHERE user='$username' AND pass='$password'");
$num = mysql_num_rows($query);
if($num == 1)
{
while($list=mysql_fetch_assoc($query))
{ $output = $list;
}
mysql_close();
echo json_encode($output);
?>
edit the final "echou" to echo and add
header('Content-Type: application/json');

You have to create webservice in which php code is written. web service can be soap and Rest. and you have to write url of webservice in http client object.
By doing this you can connect android and mysql.
HttpPost postD=new HttpPost("url");

Have you given Internet Permission in your android manifest?
<uses-permission android:name="android.permission.INTERNET" />

Related

PHP: undefined index error but variable has correct value when printed

I'm passing some values from an android app to a PHP script. I get an undefined index error in my PHP script but the variables have the correct values when I print them out from within the script. I want these errors gone but I can't figure out why they are there in the first place. Here is how they are passed to the PHP script.
Java Code
//build url data to be sent to server
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("username",username));
nameValuePairs.add(new BasicNameValuePair("password",password));
String result = "";
InputStream is = null;
//http post
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://10.0.2.2/PasswordCheck.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs,"utf-8"));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
}catch(Exception e){
Log.e("Connection", "Error in http connection "+e.toString());
}
PHP Code:
<?php
mysql_connect("localhost", "root", "") or die("could not connect to mysql");
mysql_select_db("drop-in") or die("database not found");
if(isset($_POST["username"])){
$username = $_POST["username"];
}
if(isset($_POST["password"])){
$suppliedPassword = $_POST["password"];
}
$databasePassword = "";
$output = "false";
$query = mysql_query("SELECT Password FROM users WHERE Username = '$username'") or die("query failed");
if(mysql_num_rows($query) > 0){
$row = mysql_fetch_assoc($query);
$databasePassword = $row['password'];
if($databasePassword == $suppliedPassword)
{
$output = "true";
}
}
print($output);
mysql_close();
?>
EDIT: added PHP script (they aren't in the same file, the code tags are misbehaving)
Turns out it was a simple spelling error. I used a lower case 'p' in the word 'password' in my loop instead of an uppercase. Odd that it caused the error that it did.

Login form with PHP in Android

I have written PHP code to fetch data from Database. It get the login values. (username & password). I connect it through mysql server/localhost. when I run this PHP code it always show the "0". It means it doesn't get the data from Database. Why is that?
Here my PHP code:
<?php
$hostname_localhost ="localhost";
$database_localhost ="gpsvts_geotrack";
$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['uname'];
$password = $_POST['passwd'];
$query_search = "select 'uname' & 'passwd' from user_master where uname = '.$username.' AND passwd = '.$password.'";
$query_exec = mysql_query($query_search) or die(mysql_error());
$rows = mysql_num_rows($query_exec);
//echo $rows;
if($rows == 0) {
echo "No Such User Found";
}
else {
echo "User Found";
}
?>
I put this in my wamp server www folder.when i run this php file wamp server localhost it always say "no such user found".
i used this php file for fetching data from db to connect android login form. it contain two fields. which are username & password.
here I give my android login code.
b = (Button)findViewById(R.id.Button01);
et = (EditText)findViewById(R.id.username);
pass= (EditText)findViewById(R.id.password);
tv = (TextView)findViewById(R.id.tv);
b.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
dialog = ProgressDialog.show(AndroidPHPConnectionDemo.this, "",
"Validating user...", true);
new Thread(new Runnable() {
public void run() {
login();
}
}).start();
}
});
}
void login(){
try{
httpclient=new DefaultHttpClient();
httppost= new HttpPost("http://10.0.2.2//new/nuwan1.php"); // make sure the url is correct.
//add your data
nameValuePairs = new ArrayList<NameValuePair>(2);
// Always use the same variable name for posting i.e the android side variable name and php side variable name should be similar,
nameValuePairs.add(new BasicNameValuePair("username",et.getText().toString().trim())); // $Edittext_value = $_POST['Edittext_value'];
nameValuePairs.add(new BasicNameValuePair("password",pass.getText().toString().trim()));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
//Execute HTTP Post Request
response=httpclient.execute(httppost);
// edited by James from coderzheaven.. from here....
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(AndroidPHPConnectionDemo.this,"Login Success", Toast.LENGTH_SHORT).show();
}
});
startActivity(new Intent(AndroidPHPConnectionDemo.this, UserPage.class));
}else{
showAlert();
}
}catch(Exception e){
dialog.dismiss();
System.out.println("Exception : " + e.getMessage());
}
}
public void showAlert(){
AndroidPHPConnectionDemo.this.runOnUiThread(new Runnable() {
public void run() {
AlertDialog.Builder builder = new AlertDialog.Builder(AndroidPHPConnectionDemo.this);
builder.setTitle("Login Error.");
builder.setMessage("User not Found.")
.setCancelable(false)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
}
});
AlertDialog alert = builder.create();
alert.show();
}
});
}
Always I got the alart no such user found & php response is No such user found
why is that?
pls help me.
I used following php code
<?php
$un=$_POST['uname'];
$pw=$_POST['passwd'];
//connect to the db
$host="localhost"; // Host name
$user="root"; // Mysql username
$pswd=""; // Mysql password
$db="gpsvts_geotrack"; // Database name
$tbl_name="user_master"; // Table name
$conn = mysql_connect($host, $user, $pswd);
mysql_select_db($db, $conn);
//run the query to search for the username and password the match
$query = "SELECT * FROM $tbl_name WHERE uname = '$un' AND passwd= '$pw'";
//$query = "SELECT uid FROM $tbl_name WHERE uname = '$un' AND passwd = '$pw'";
$result = mysql_query($query) or die("Unable to verify user because : " . mysql_error());
//this is where the actual verification happens
if(mysql_num_rows($result) > 0)
echo mysql_result($result,0); // for correct login response
else
echo 0; // for incorrect login response
?>
Then return uid as response. but not validating user. Is there PHP code wrong or android code wrong. I want to match the values user enter & database get. Is that happen in here.
if not give me correct thing.
In your program you are passing from your side is:
nameValuePairs.add(new BasicNameValuePair("username",et.getText().toString().trim())); // $Edittext_value = $_POST['Edittext_value'];
nameValuePairs.add(new BasicNameValuePair("password",pass.getText().toString().trim()));
And you are trying to fetch from PHP side is:
$un=$_POST['uname'];
$pw=$_POST['passwd'];
So Change The Name in nameValuePairs are passed with this:
nameValuePairs.add(new BasicNameValuePair("uname",et.getText().toString().trim())); // $Edittext_value = $_POST['Edittext_value'];
nameValuePairs.add(new BasicNameValuePair("passwd",pass.getText().toString().trim()));
If I'm not mistaken it should be like this because your post variables are spelled different than what you're putting in the name value pairs.
nameValuePairs.add(new BasicNameValuePair("uname",et.getText().toString().trim())); // $Edittext_value = $_POST['Edittext_value'];
nameValuePairs.add(new BasicNameValuePair("passwd",pass.getText().toString().trim()));

Connecting mysql database with Android app

I have a problem connecting database with Android app. I am trying to implement this tutorial. Everything seems to be fine but I neither get any success not an error.
There is a button listener which on clicking does a post to a PHP file and gets the result. Here is the code for it:-
ok.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("username", un.getText().toString()));
postParameters.add(new BasicNameValuePair("password", pw.getText().toString()));
//String valid = "1";
String response = null;
try {
response = CustomHttpClient.executeHttpPost("http://10.0.2.2/check.php", postParameters);
String res=response.toString();
Log.d("res:", res);
// res = res.trim();
res= res.replaceAll("\\s+","");
//error.setText(res);
if(res.equals("1"))
error.setText("Correct Username or Password");
else
error.setText("Sorry!! Incorrect Username or Password");
} catch (Exception e) {
un.setText(e.toString());
}
}
});
Here is the http post method:-
public static String executeHttpPost(String url, ArrayList<NameValuePair> postParameters) throws Exception {
BufferedReader in = null;
try {
HttpClient client = getHttpClient();
HttpPost request = new HttpPost(url);
UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(postParameters);
request.setEntity(formEntity);
HttpResponse response = client.execute(request);
in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
StringBuffer sb = new StringBuffer("");
String line = "";
String NL = System.getProperty("line.separator");
while ((line = in.readLine()) != null) {
sb.append(line + NL);
}
in.close();
String result = sb.toString();
Log.d("postMethodReturn", result);
return result;
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
The PHP code is as below:-
<?php
$un=$_POST['username'];
$pw=$_POST['password'];
//connect to the db
$user = "xyz";
$pswd = "xyz";
$db = "mydb";
$host = "localhost";
$conn = mysql_connect($host, $user, $pswd);
mysql_select_db($db);
//run the query to search for the username and password the match
$query = "SELECT * FROM mytable WHERE user = '$un' AND pass = '$pw'";
$result = mysql_query($query) or die("Unable to verify user because : " . mysql_error());
//this is where the actual verification happens
if(mysql_num_rows($result) --> 0)
echo 1; // for correct login response
else
echo 0; // for incorrect login response
?>
Is there any bug in the program? I tried logging the intermediate values of res (http response) in activity code and result in the execute post method, but nothing is being logged. Tried changing "localhost" to "127.0.0.1" and also into a publicly available webhost, with all the database environment, but no success. All these on emulator and with public host, tried with real device too. Server seems to be running when checked from browser. Database exists with the values. All services running (apache, mysql).
The main problem is that there is no error! Any suggestions what is going wrong?
Couldn't find anyone with the same problem.
the problem was --> in the PHP code. changed it to == or > and everything works fine!

User Authentation using php and mysql

guys i am working on android 2.2 i am stuck where the user need to be authenticated with his use name and password
below is my code
PHP code:
<?php
$un=$_POST['userid'];
$pw=$_POST['password'];
mysql_connect("localhost","root","");
mysql_select_db("myhealthcare");
$sql=mysql_query("select userid,password from register where userid='$un' and password='$pw'");
while($row=mysql_fetch_assoc($sql))
$output[]=$row;
print(json_encode($output));
mysql_close();
?>
Java Code:
ArrayList<NameValuePair> nvp = new ArrayList<NameValuePair>();
nvp.add(new BasicNameValuePair("userid", userid.getText().toString()));
nvp.add(new BasicNameValuePair("password", password.getText().toString()));
String un = userid.getText().toString();
String pass = password.getText().toString();
System.out.println("user name is " + un);
System.out.println("password is " +pass);
// Log.e(""+sid.getText().toString(),"0");
// Log.e(""+sname.getText().toString(),"0");
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://10.0.2.2/login.php");
httppost.setEntity(new UrlEncodedFormEntity(nvp));
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());
}
try {
BufferedReader bf = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
sb = new StringBuilder();
sb.append(bf.readLine()+ "\n");
String line="0";
while ((line = bf.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result=sb.toString();
System.out.println("value of result " +result);
}catch(Exception e){
Log.e("log_tag", "Error converting result "+e.toString());
}
String unm,pwd;
try {
jArray = new JSONArray(result);
JSONObject json_data = null;
for(int i=0;i<jArray.length();i++){
json_data = jArray.getJSONObject(i);
unm = json_data.getString("userid");
pwd = json_data.getString("password");
System.out.println("databse user name is " +unm);
System.out.println("databse password is " +pwd);
}
} catch(JSONException e1){
Toast.makeText(getBaseContext(), "No details Found" ,Toast.LENGTH_LONG).show();
} catch (ParseException e1) {
e1.printStackTrace();
}
i am able to fetch the value from database but i am not able to compare with user entered values please help
I would do the PHP sometheing like this instead, to do the authentication on the server and not passing the login info back and forth:
<?php
$un=mysql_real_escape_string($_POST['userid']);
$pw=mysql_real_escape_string($_POST['password']);
mysql_connect("localhost","root","");
mysql_select_db("myhealthcare");
$result=mysql_query("select userid from register where userid='$un' and password='$pw'");
if (mysql_num_rows($result) == 0) {
print("Not authorized"); // Or send a json-encoded object containing the message
} else {
print("Authorized");
}
mysql_close();
?>
Update
Use PHP's mysql_real_escape_string() before running any data input by a user in your SQL. Otherwise you open your DB to SQL-injections, which is really bad.

Send data from android to mysql

I could really need some help to my project.
I have an android app, that scans for wireless networks. I want to upload this data to a mysql database.
Android have database class:
public class Database {
public static void putServerData(String building, String floor, String room, String address, String signal){
String db_url = "http://**(IP ADDRESS)**/setdata.php";
#SuppressWarnings("unused")
InputStream is = null;
ArrayList<NameValuePair> request = new ArrayList<NameValuePair>();
request.add(new BasicNameValuePair("building",building));
request.add(new BasicNameValuePair("floor",floor));
request.add(new BasicNameValuePair("room",room));
request.add(new BasicNameValuePair("address",address));
request.add(new BasicNameValuePair("signal",signal));
try
{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(db_url);
httppost.setEntity(new UrlEncodedFormEntity(request));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
}catch(Exception e){
}
}
This is called by:
try {
Database.putServerData(building,floor, room, array1.get(1).toString(), array2.get(2).toString());
} catch (Exception e) {
Log.e("test", "test");
}
The server is a Win7 machine, with apache php and mysql
The setdata.php file:
<?php
$con = mysql_connect("localhost","root","pass");
if(!$con)
{
echo 'Not connected';
echo ' - ';
}else
{
echo 'Connection Established';
echo ' - ';
}
$db = mysql_select_db("android");
if(!$db)
{
echo 'No database selected';
}else
{
echo 'Database selected';
}
$building = $_POST['building'];
$floor = $_POST['floor'];
$room = $_POST['room'];
$ap_mac1 = $_POST['ap_mac1'];
$ap_strength1 = $_POST['ap_strength1'];
$ap_mac2 = $_POST['ap_mac2'];
$ap_strength2 = $_POST['ap_strength2'];
$ap_mac3 = $_POST['ap_mac3'];
$ap_strength3 = $_POST['ap_strength3'];
$ap_mac4 = $_POST['ap_mac4'];
$ap_strength4 = $_POST['ap_strength4'];
$ap_mac5 = $_POST['ap_mac5'];
$ap_strength5 = $_POST['ap_strength5'];
echo ($_POST['building']);
mysql_query("INSERT INTO wifiscan VALUES($nextid, '$building','$floor','$room','$ap_mac1','$ap_strength1','$ap_mac2','$ap_strength2', '$ap_mac3', '$ap_strength3', '$ap_mac4', '$ap_strength4', '$ap_mac5', '$ap_strength5')");
mysql_close(); ?>
This is not working. Im not sure i select the database in the correct way, could that be the problem?
Maybe this isnt so clear and ill will explain it further if you want.
Use some Log and maybe sprintfs to figure out what is exactly going on.
I#d start with the PHP. Try to open the URL from your browser and put some outputs in the PHP to see if everything works fine here. Post your results and you will probably get further help.

Categories