0% found this document useful (0 votes)
392 views

PHP MYSQL-Android Studio

This document provides an example of integrating PHP and MySQL with an Android application to access a web server's database. It describes creating a MySQL database on a web server with a table containing user credentials. It then shows PHP code to connect to the database and fetch records based on GET or POST parameters from Android. It includes Android code using HTTP GET and POST methods to pass username and password to the PHP file and receive the response to check login credentials.

Uploaded by

myhddex tern
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
392 views

PHP MYSQL-Android Studio

This document provides an example of integrating PHP and MySQL with an Android application to access a web server's database. It describes creating a MySQL database on a web server with a table containing user credentials. It then shows PHP code to connect to the database and fetch records based on GET or POST parameters from Android. It includes Android code using HTTP GET and POST methods to pass username and password to the PHP file and receive the response to check login credentials.

Uploaded by

myhddex tern
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 23

PHP-MYSQL—Android Studio

Contoh penggunaan MYSQL pada aplikasi android studio


Introduction
• how you can integrate PHP and MYSQL with your android application.
This is very useful in case you have a webserver, and you want to
access its data on your android application.
• MYSQL is used as a database at the webserver and PHP is used to
fetch data from the database. Our application will communicate with
the PHP page with necessary parameters and PHP will contact MYSQL
database and will fetch the result and return the results to us.
Skema
• Buatlah database MYSql di webserver (local atau online)
• Buat Table dengan kolom:
• Username CHAR(30),Password CHAR(30),Role CHAR(30)

• Isi dengan:
• INSERT INTO table1 (FirstName, LastName, Age) VALUES ('admin',
'admin','adminstrator')
PHP - GET and POST methods
• PHP is also used to fetch the record from the mysql database once it
is created. In order to fetch record some information must be passed
to PHP page regarding what record to be fetched.
• The first method to pass information is through GET method in
which $_GET command is used. The variables are passed in the url
and the record is fetched.
File PHP
<?php
$con=mysqli_connect("example.com","username","password","database name");

if (mysqli_connect_errno($con)) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

$username = $_GET['username'];
$password = $_GET['password'];
$result = mysqli_query($con,"SELECT Role FROM table1 where Username='$username'
and Password='$password'");
$row = mysqli_fetch_array($result);
$data = $row[0];

if($data){
echo $data;
}
mysqli_close($con);
?>
Android - Connecting MYSQL
Connecting Via Get Method
• There are two ways to connect to MYSQL via PHP page. The first one
is called Get method. We will use HttpGet and HttpClient class to
connect.

URL url = new URL(link);


HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet();
request.setURI(new URI(link));
Android - Connecting MYSQL
Connecting Via Get Method
After that you need to call execute method of HttpClient class and
receive it in a HttpResponse object. After that you need to open
streams to receive the data.

HttpResponse response = client.execute(request);


BufferedReader in = new BufferedReader
(new InputStreamReader(response.getEntity().getContent()));
Connecting Via Post Method
• In the Post method, the URLEncoder,URLConnection class will be
used. The urlencoder will encode the information of the passing
variables.

URL url = new URL(link);


String data = URLEncoder.encode("username", "UTF-8")
+ "=" + URLEncoder.encode(username, "UTF-8");
data += "&" + URLEncoder.encode("password", "UTF-8")
+ "=" + URLEncoder.encode(password, "UTF-8");
URLConnection conn = url.openConnection();
Connecting Via Post Method
• The last thing you need to do is to write this data to the link. After
writing, you need to open stream to receive the responded data.

OutputStreamWriter wr = new
OutputStreamWriter(conn.getOutputStream());
wr.write( data );
BufferedReader reader = new BufferedReader(new
InputStreamReader(conn.getInputStream()));
Example
• PHP - MYSQL part
• In this example a database with the name of temp has been created at
000webhost.com. In that database, a table has been created with the name
of table1. This table has three fields. (Username, Password, Role). The table
has only one record which is ("admin","admin","administrator").
Example
<?php
$con=mysqli_connect("mysql10.000webhost.com","username","password","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 FROM table1 where
Username='$username' and Password='$password'");
$row = mysqli_fetch_array($result);
$data = $row[0];
if($data){
echo $data;
}
mysqli_close($con);
?>
Android Part
• To experiment with this example , you need to run this on an actual
device on which wifi internet is connected.
Steps Description

1 You will use Android studio IDE to create an Android application and name it as PHPMYSQL under
a package com.example.phpmysql.
2 Modify src/MainActivity.java file to add Activity code.
3 Create src/SiginActivity.java file to add PHPMYSQL code.
4 Modify layout XML file res/layout/activity_main.xml add any GUI component if required.

5 Modify res/values/string.xml file and add necessary string components.


6 Modify AndroidManifest.xml to add necessary permissions.
7 Run the application and choose a running android device and install the application on it and
verify the results.
src/com.example.phpmysql/MainActivity.java.
package com.example.phpmysql;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

public class MainActivity extends Activity {

private EditText usernameField,passwordField;


private TextView status,role,method;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

usernameField = (EditText)findViewById(R.id.editText1);
passwordField = (EditText)findViewById(R.id.editText2);

status = (TextView)findViewById(R.id.textView6);
role = (TextView)findViewById(R.id.textView7);
method = (TextView)findViewById(R.id.textView9);
}

public void login(View view){


String username = usernameField.getText().toString();
String password = passwordField.getText().toString();
method.setText("Get Method");
new SigninActivity(this,status,role,0).execute(username,password);

public void loginPost(View view){


String username = usernameField.getText().toString();
String password = passwordField.getText().toString();
method.setText("Post Method");
new SigninActivity(this,status,role,1).execute(username,password);
}
}
src/com.example.phpmysql/SigninActivity.java
package com.example.phpmysql;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

public class MainActivity extends Activity {

private EditText usernameField,passwordField;


private TextView status,role,method;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

usernameField = (EditText)findViewById(R.id.editText1);
passwordField = (EditText)findViewById(R.id.editText2);

status = (TextView)findViewById(R.id.textView6);
role = (TextView)findViewById(R.id.textView7);
method = (TextView)findViewById(R.id.textView9);
}

public void login(View view){


String username = usernameField.getText().toString();
String password = passwordField.getText().toString();
method.setText("Get Method");
new SigninActivity(this,status,role,0).execute(username,password);

public void loginPost(View view){


String username = usernameField.getText().toString();
String password = passwordField.getText().toString();
method.setText("Post Method");
new SigninActivity(this,status,role,1).execute(username,password);
}
}
src/com.example.phpmysql/SigninActivity.java
package com.example.phpmysql;
@Override
import java.io.BufferedReader;
protected String doInBackground(String... arg0) {
import java.io.InputStreamReader;
import java.io.OutputStreamWriter; if(byGetOrPost == 0){ //means by Get Method
import java.net.URI;
import java.net.URL; try{
import java.net.URLConnection; String username = (String)arg0[0];
import java.net.URLEncoder; String password = (String)arg0[1];
String link = "http://myphpmysqlweb.hostei.com/login.php?username="+username+"&
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient; password="+password;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient; URL url = new URL(link);
HttpClient client = new DefaultHttpClient();
import android.content.Context; HttpGet request = new HttpGet();
import android.os.AsyncTask;
request.setURI(new URI(link));
import android.widget.TextView;
HttpResponse response = client.execute(request);
public class SigninActivity extends AsyncTask{ BufferedReader in = new BufferedReader(new
private TextView statusField,roleField; InputStreamReader(response.getEntity().getContent()));
private Context context;
private int byGetOrPost = 0; StringBuffer sb = new StringBuffer("");
String line="";
//flag 0 means get and 1 means post.(By default it is get.)
public SigninActivity(Context context,TextView statusField,TextView
roleField,int flag) { while ((line = in.readLine()) != null) {
this.context = context; sb.append(line);
this.statusField = statusField; break;
this.roleField = roleField; }
byGetOrPost = flag;
}
in.close();
protected void onPreExecute(){ return sb.toString();
} } catch(Exception e){
return new String("Exception: " + e.getMessage());
}
src/com.example.phpmysql/SigninActivity.java
} else{ @Override
try{ protected void onPostExecute(String result){
String username = (String)arg0[0];
this.statusField.setText("Login Successful");
String password = (String)arg0[1];
this.roleField.setText(result);
String link="http://myphpmysqlweb.hostei.com/loginpost.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());
}
}
}
Gradle
• Add the following content to build.gradle and rebuild the whole
project.

android {
useLibrary 'org.apache.http.legacy'
}
<EditText
android:id="@+id/editText1"
android:layout_width="wrap_content"

activity_main.xml. android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:layout_marginTop="44dp"
android:ems="10" >
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout <requestFocus android:layout_width="wrap_content" />
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" </EditText>
android:layout_width="match_parent"
android:layout_height="match_parent" <TextView
android:paddingBottom="@dimen/activity_vertical_margin"
android:id="@+id/textView1"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin" android:layout_width="wrap_content"
android:paddingTop="@dimen/activity_vertical_margin" android:layout_height="wrap_content"
tools:context=".MainActivity" > android:layout_alignBottom="@+id/editText1"
android:layout_alignParentLeft="true"
<EditText android:text="@string/Username" />
android:id="@+id/editText2"
android:layout_width="wrap_content" <TextView
android:layout_height="wrap_content" android:id="@+id/textView3"
android:layout_alignRight="@+id/editText1"
android:layout_width="wrap_content"
android:layout_below="@+id/editText1"
android:layout_marginTop="25dp" android:layout_height="wrap_content"
android:ems="10" android:layout_alignParentTop="true"
android:inputType="textPassword" > android:layout_centerHorizontal="true"
</EditText> android:text="@string/App"
android:textAppearance="?android:attr/textAppearanceLarge" />
activity_main.xml.
<TextView
<TextView android:id="@+id/textView4"
android:id="@+id/textView7"
android:layout_width="wrap_content" android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="@+id/textView5" android:layout_height="wrap_content"
android:layout_alignLeft="@+id/textView6" android:layout_alignLeft="@+id/textView8"
android:text="@string/Role"
android:textAppearance="?android:attr/textAppearanceMedium" android:layout_below="@+id/button1"
android:textSize="10sp" />
android:layout_marginTop="86dp"
<TextView
android:id="@+id/textView5" android:text="@string/LoginStatus" />
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/textView6"
android:layout_marginTop="27dp"
android:layout_toLeftOf="@+id/editText1" <TextView
android:text="@string/LoginRole" /> android:id="@+id/textView6"
<TextView android:layout_width="wrap_content"
android:id="@+id/textView8"
android:layout_width="wrap_content" android:layout_height="wrap_content"
android:layout_height="wrap_content"
android:layout_above="@+id/textView6" android:layout_alignTop="@+id/textView4"
android:layout_alignLeft="@+id/textView5" android:layout_centerHorizontal="true"
android:layout_marginBottom="27dp"
android:text="@string/method" /> android:text="@string/Status"
activity_main.xml. <Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:textAppearance="?android:attr/textAppearanceMe android:layout_height="wrap_content"
dium"
android:textSize="10sp" /> android:layout_alignBaseline="@+id/button2"
android:layout_alignBottom="@+id/button2"
<TextView
android:id="@+id/textView9" android:layout_alignLeft="@+id/textView2"
android:layout_width="wrap_content" android:onClick="login"
android:layout_height="wrap_content" android:text="@string/LoginGet" />
android:layout_alignBottom="@+id/textView8"
android:layout_alignLeft="@+id/textView6"
android:text="@string/Choose" <TextView
android:textAppearance="?android:attr/textAppearanceMe android:id="@+id/textView2"
dium" android:layout_width="wrap_content"
android:textSize="10sp" />
android:layout_height="wrap_content"
<Button android:layout_alignBaseline="@+id/editText2"
android:id="@+id/button2" android:layout_alignBottom="@+id/editText2"
android:layout_width="wrap_content"
android:layout_height="wrap_content" android:layout_alignParentLeft="true"
android:layout_centerVertical="true" android:text="@string/Password" />
android:layout_toRightOf="@+id/textView6"
android:onClick="loginPost"
android:text="@string/LoginPost" /> </RelativeLayout>
Strings.xml.
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">PHPMYSQL</string>
<string name="action_settings">Settings</string>
<string name="hello_world">Hello world!</string>
<string name="Username">Username</string>
<string name="Password">Password</string>
<string name="LoginGet">Login - Get</string>
<string name="LoginPost">Login - Post</string>
<string name="App">Login Application</string>
<string name="LoginStatus">Login Status</string>
<string name="LoginRole">Login Role</string>
<string name="Status">Not login</string>
<string name="Role">Not assigned</string>
<string name="method">Login Method</string>
<string name="Choose">Choose Method</string>
</resources>
AndroidManifest.xml.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.phpmysql" >
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.example.phpmysql.MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Coba - wireframe

You might also like