Android - Connecting to MYSQL (Get Method)

Discussion in 'Android' started by TelVerde, Aug 19, 2017.

  1. TelVerde

    TelVerde Material Design addicted Staff Member

    [​IMG]
    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:
    URL url =new URL(link);HttpClient client =newDefaultHttpClient();HttpGet request =newHttpGet();
    
    request.setURI(new URI(link));


    ...call execute method of HttpClient class and receive it in a HttpResponse object.
    Code:
    HttpResponse response = client.execute(request);
    
    BufferedReader in = new BufferedReader
    (new InputStreamReader(response.getEntity().getContent()));


    Connecting Via Post Method

    Code:
    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(); 


    Code:
    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.


    Code:
    <?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);
    ?>



    More info and complete Android - PHP/MYSQL tutorial



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