Cellphonesguide.net
Login or Register to remove ads! You're browsing our forum and website as a Guest meaning you can only see a portion of the forum in read-only mode.
Android Android Games iOS iPhone Samsung Galaxy Google Pixel OnePlus Huawei Xiaomi
Discord Social FB Group Games Ask a Question Apps

Android - Connecting to MYSQL (Get Method)

TelVerde

  • Material Design addicted
  • ***
  • 170
Android - Connecting to MYSQL (Get Method)
« on: August 19, 2017, 03:35:47 PM »
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.
Code: [Select]
URL url =new URL(link);HttpClient client =newDefaultHttpClient();HttpGet request =newHttpGet();

request.setURI(new URI(link));
[/SIZE]

...call execute method of HttpClient class and receive it in a HttpResponse object.
Code: [Select]
HttpResponse response = client.execute(request);

BufferedReader in = new BufferedReader
(new InputStreamReader(response.getEntity().getContent()));
[/SIZE]

Connecting Via Post Method

Code: [Select]
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();
[/SIZE]

Code: [Select]
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());

wr.write( data );
BufferedReader reader = new BufferedReader(new
InputStreamReader(conn.getInputStream()));    

The php page has been given below which takes parameters by post method.[/SIZE]

Code: [Select]

   $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);
?>
[/SIZE]


More info and complete Android - PHP/MYSQL tutorial



--
Ref: www.tutorialspoint.com/android/android_php_mysql.htm