1

Hi I am new to android and I am developing an app which has a login screen.

I have tried many tutorials but I am not sure how to connect the mysql database to my android app. In all the tutorials they have used php to connect the android app to the database.

What I want to know is that where exactly do I need to place the php file and where and how I need to create the php file.

I am creating the database using mysql workbench.

I am using eclipse 4.2 to write the java code.

Hi i am using the following code to check whether the user name i entered is correct or not along with the php code but the problem is that it always gives incorrect username.

String response = null;
try {
response = CustomHttpClient.executeHttpPost("http://192.168.3.27/abc/check.php", postParameters);  //Enetr Your remote PHP,ASP, Servlet file link
String res=response.toString();
// res = res.trim();
res= res.replaceAll("\\s+","");
//error.setText(res);
error.setText(res);
if(res.equals("1")){
    Intent myIntent = new Intent(LoginActivity.this, HomeActivity.class);           
startActivity(myIntent);

}
else
error.setText("Sorry!! Incorrect Username or Password");

This is my php code.

<?php
$un=$_POST['username'];
$pw=$_POST['password'];
//connect to the db
$user = ‘root’;
$pswd = ‘root’;
$db = ‘mylogin’;
$conn = mysql_connect(‘localhost’, $user, $pswd);
mysql_select_db($db, $conn);
//run the query to search for the username and password the match
$query = “SELECT * FROM userpass WHERE login_id = ‘$un’ AND login_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
?>
1
  • 1
    does your app has some kind of communication with server side to let loging in the user? if so then you need to upload the php file on the server. Commented Jan 16, 2013 at 5:53

4 Answers 4

2

Here is the complete tutorial which you are searching for..

as like your normal html page, post the login values from the android device to the url and authenticate in php file as like the example

Sign up to request clarification or add additional context in comments.

Comments

1

where exactly do i need to place the php file

You need to place PHP file in server. (You can use localhost i.e., your machine but for devices outside you need to keep it on a webserver which you need to purchase a domain and hosting services.)

where and how i need to create the php file.

You can create a PHP file in you machine itself. Its as simple as creating a text file but with an extension of .php. Using a wamp on windows (LAMP for linux)you can test it. It has a MySQL in it. LAMP and WAMP will have apache server by default.

Soon after you are finished with writing you php code and testing you can transfer the files through FTP into your webserver. Now to configure the MySQL database you can actually use a control panel at the webserver.

You need to use URL for android application to link the PHP files in turn these PHP files interact with MysQL. for a login lets think like you have created a php file as login.php. On your localhost you can refer it to as http://localhost/myapp/login.php If you need to get it on a webserver which you purchase then you URL will have http://www.yourwebsite.com/myapp/login.php. note that myapp is just a folder where you have uploaded your php files.

Now its just a way by which you can actually have a PHP and MySQL for you android application. I think that tutorials have taught you about using php and mysql connections. For Data exchange you need to know about XML or JSON I think tutorials followed had given you an introduction about it.

You even have a plugin for eclipse to work with php. Just get a help over internet on how to install it. This video might help you.

6 Comments

i havent installed wamp server only tomcat server and mysql server seperately now where to place and host the php file?
If you open wamp folder in C drive you will find a folder www there you can place your php file. Access you file as http://localhost/yourfilename.php.
hi @JJPA do you know the solution to the above problem??
Are you sure you have passed the parameters(POST) correctly? And try to echo the username and password and check weather you get the values correctly.
i am following this tutorial webdesignergeeks.com/mobile/android/…
|
1

I'd like to brief raheel's answer, but in my own way. The important thing is that you need a server-client communication to access your my sql. For that you need to create a server which responds to requests from your android app. Your request shall be as follows

HttpClient httpclient = new DefaultHttpClient();
HttpGet httpget = new HttpGet("http://example.com/script.php?var1=androidprogramming");
try {
    HttpResponse response = httpclient.execute(httpget);
    if(response != null) {
        String line = "";
        InputStream inputstream = response.getEntity().getContent();
        line = convertStreamToString(inputstream);
        Toast.makeText(this, line, Toast.LENGTH_SHORT).show();
    } else {
        Toast.makeText(this, "Unable to complete your request", Toast.LENGTH_LONG).show();
    }
} catch (ClientProtocolException e) {
    Toast.makeText(this, "Caught ClientProtocolException", Toast.LENGTH_SHORT).show();
} catch (IOException e) {
    Toast.makeText(this, "Caught IOException", Toast.LENGTH_SHORT).show();
} catch (Exception e) {
    Toast.makeText(this, "Caught Exception", Toast.LENGTH_SHORT).show();
}

the consuming of output will be :

private String convertStreamToString(InputStream is) {
    String line = "";
    StringBuilder total = new StringBuilder();
    BufferedReader rd = new BufferedReader(new InputStreamReader(is));
    try {
        while ((line = rd.readLine()) != null) {
            total.append(line);
        }
    } catch (Exception e) {
        Toast.makeText(this, "Stream Exception", Toast.LENGTH_SHORT).show();
    }
    return total.toString();
}

Then the server side can be like:

$connection = mysql_connect(DB_HOST,DB_USER,DB_PASSWORD) or die('Unable to connect');
$db = mysql_selectdb(DB_NAME,$connection) or die('Database not found');
if(isset($_GET['var'])) :
    $query = "SELECT [a few parameters] FROM [some table] WHERE [some conditions]";
    $resultset = mysql_query($query);
    $row = mysql_fetch_array($resultset)
    echo $row['[column name]'];
else:
    echo "No get Request Received";
endif;

These are just snippets from which you can build on

2 Comments

i have a tomcat server installed on my system how to connect mysql database using it?
just use it to host your server code from there, then call the server link from android which points to the local server
1

For this purpose you should create a php application and host it on a server. then using php create functions(or links available online) which will be hit by android application and they(functions) will output the data as json_encoded which is required by android. You can easily use this way to setup your application.
I usually use Codeigniter framework and it works like this.

myapp/
    system/
    application/
         controllers/
             mycontroller

mycontroller has some functions like this

function test(){
    $username = $this->uri->segment(3);
    $password = $this->uri->segment(4);
    // other stuff like fetch data from db table in the variable $data

    header('Content-Type: application/json');
    echo json_encode($data);
}

And android needs this

http://testdomain/myapp/index.php/mycontroller/test/username/password

EDITS :
if you are usig plain php you can do it like this

  1. Create a folder on your server.
  2. create a file test.php create a connection file connection.php
  3. include 2nd file in the first.
  4. create a function in test.php named

include('connection.php');

function index($username,$password)
{
    //query database table
    //if result is success full
    //  $data   =   array('message'=>'login success');
    //else
    //  $data   =   array('message'=>'login failed');
    //
    //header('Content-Type: application/json');
    //echo json_encode($data);  
}

from the address bar you can access it like this

 http://tomcatserver/test.php/index/testuser/testpassword

You should do some research how php works

3 Comments

I have a tomcat server installed.
you can set up your php application there.
how to set it up i am new to both php and tomcat server

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.