Web&App/웹

Android PHP MySQL 로그인 예제 - 데이터베이스 값 가져오기 [GET 방식] , HTTP REST API

15051015 2020. 12. 9. 17:55

2020/06/30 - [인턴/웹] - Android PHP MySQL 회원가입 예제 - 데이터베이스에 값 입력하기

 

Android PHP MySQL 회원가입 예제 - 데이터베이스에 값 입력하기

아래의 블로그를 보고 참고하여 만들었습니다. https://webnautes.tistory.com/828 Android PHP MySQL 예제 - 데이터베이스에 데이터 입력하기 안드로이드 앱이 PHP 프로그램을 매개로 하여 MySQL 데이터베이스

15051015.tistory.com

웹 서버 환경은 라즈베리파이 4B 에서 APM (apache + php + mysql) 을 구축하였습니다.

 

앱은 안드로이드 스튜디오를 이용하여 만들었습니다.

 

 

라즈베리파이에 아파치, php, mysql을 모두 설치한 후의 과정입니다.

 

회원가입 과정은 위 링크에서 확인하실 수 있습니다! 

 

php 코드

 

( 라즈베리의 /var/www/html 폴더에 넣으면 됩니다. )

 

login.php

 

<?php
   error_reporting(E_ALL); 
    ini_set('display_errors',1); 

    include('dbcon.php');

   //  $android = strpos($_SERVER['HTTP_USER_AGENT'], "Android");	

    $ID= isset($_GET['ID']) ? $_GET['ID'] : '';    
    $PW= isset($_GET['PW']) ? $_GET['PW'] : ''; 
      $android = strpos($_SERVER['HTTP_USER_AGENT'], "Android");

if ($ID != "" ){ 
     $sql ="select * from PERSON where ID='$ID' and PW='$PW'"; 
     $stmt = $con->prepare($sql);
     $stmt->execute();
 
    if ($stmt->rowCount() == 0){
        echo "'";
        echo $ID,", ",$PW;
        echo "'은 찾을 수 없습니다.";
    }else{
   	$data = array(); 
        while($row=$stmt->fetch(PDO::FETCH_ASSOC)){
        	extract($row);
         	echo '1';
        }
        if (!$android) {
            echo "<pre>"; 
            print_r($data); 
            echo '</pre>';
        }else {
            header('Content-Type: application/json; charset=utf8');
            $json = json_encode(array("webnautes"=>$data), JSON_PRETTY_PRINT+JSON_UNESCAPED_UNICODE);
            echo $json;
        }
    }
}
else {
    echo ". ";
}
?>


<html>
   <body>
   
      <form action="<?php $_PHP_SELF ?>" method="GET">
         아이디: <input type = "text" name = "ID" />
         비밀번호: <input type = "text" name = "PW" />
         <input type = "submit" />
      </form>
   
   </body>
</html>

 

dbcon.php

 

<?php

    $host = 'localhost';
    $username = 'root'; # MySQL 계정 아이디
    $password = 'ghwndlsh'; # MySQL 계정 패스워드
    $dbname = 'testdb';  # DATABASE 이름


    $options = array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8');
    
    try {
        $con = new PDO("mysql:host={$host};dbname={$dbname};charset=utf8",$username, $password);
    } catch(PDOException $e) {
        die("Failed to connect to the database: " . $e->getMessage()); 
    }
    $con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $con->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);

    if(function_exists('get_magic_quotes_gpc') && get_magic_quotes_gpc()) { 
        function undo_magic_quotes_gpc(&$array) { 
            foreach($array as &$value) { 
                if(is_array($value)) { 
                    undo_magic_quotes_gpc($value); 
                } 
                else { 
                    $value = stripslashes($value); 
                } 
            } 
        } 
        undo_magic_quotes_gpc($_POST); 
        undo_magic_quotes_gpc($_GET); 
        undo_magic_quotes_gpc($_COOKIE); 
    } 
    header('Content-Type: text/html; charset=utf-8'); 
    #session_start();
?>

 

이 소스코드를 /var/www/html에 넣으면 됩니다.

 

라즈베리와 pc또는 핸드폰을 같은 와이파이에 접속합니다.

 

그 후 주소창에 라즈베리 ip/login.php 에 접속하시면

(ex 192.168.0.140/login.php)

 

 

위와 같은 화면이 나옵니다.

 

여기서 테스트를 해볼 수 있습니다.

[성공시 화면]
[실패시 화면]

 

위와 같이 테스트가 가능합니다.

 

GET 방식을 이용하였기 때문에, 주소창에 데이터가 입력되는것을 볼 수 있습니다.

 

 

이번에는 안드로이드에서 동작시켜 보겠습니다.

 

 

 

 

android java 코드

 

package com.example.um;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

public class MainActivity extends AppCompatActivity {
    EditText id, pw;
    Button sign_in, sign_up;

    char result2;
    private static String IP_ADDRESS = "192.168.0.128";
    private static String TAG = "phptest";

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

        id = findViewById(R.id.ID);
        pw = findViewById(R.id.PW);

        sign_in = (Button)findViewById(R.id.sign_in);
        sign_in.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                String ID = id.getText().toString();
                String PW = pw.getText().toString();

                InsertData task = new InsertData();
                task.execute("http://" + IP_ADDRESS + "/login.php", ID,PW);
                Log.d("qq",ID+PW);
            }
        });
        sign_up = (Button)findViewById(R.id.sign_up);
        sign_up.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(MainActivity.this, user_signupActivity.class);
                startActivity(intent);
            }
        });
    }
    class InsertData extends AsyncTask<String, Void, String> {
        ProgressDialog progressDialog;

        @Override
        protected void onPreExecute() {
            super.onPreExecute();

            progressDialog = ProgressDialog.show(MainActivity.this,
                    "Please Wait", null, true, true);
        }
        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);
        Log.d("qq","\n\n"+result);
            progressDialog.dismiss();
            result2 = result.toString().charAt(0);
            Log.d("qq","\n\n"+result2);
            if(result2=='1')
            {
                Toast.makeText(getApplicationContext(), "로그인 성공", Toast.LENGTH_LONG).show();
                Intent intent = new Intent(MainActivity.this, MainView.class);
                startActivity(intent);
            }
            else
            {
                Toast.makeText(getApplicationContext(), "아이디 또는 비밀번호가 다릅니다. ", Toast.LENGTH_LONG).show();
            }
            Log.d(TAG, "POST response  - " + result);
        }
        @Override
        protected String doInBackground(String... params) {
            String ID = (String)params[1];
            String PW = (String)params[2];

            String serverURL = (String)params[0];
            serverURL = serverURL+"?" + "ID=" + ID + "&PW=" + PW ;
            try {
                URL url = new URL(serverURL);
                HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();

                httpURLConnection.setReadTimeout(5000);
                httpURLConnection.setConnectTimeout(5000);
                httpURLConnection.setRequestMethod("GET");
                httpURLConnection.connect();

                int responseStatusCode = httpURLConnection.getResponseCode();
                Log.d(TAG, "GET response code - " + responseStatusCode);

                InputStream inputStream;
                if(responseStatusCode == HttpURLConnection.HTTP_OK) {
                    inputStream = httpURLConnection.getInputStream();
                }
                else{
                    inputStream = httpURLConnection.getErrorStream();
                }
                InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "UTF-8");
                BufferedReader bufferedReader = new BufferedReader(inputStreamReader);

                StringBuilder sb = new StringBuilder();
                String line = null;

                while((line = bufferedReader.readLine()) != null){
                    sb.append(line);
                }
                bufferedReader.close();
                return sb.toString();

            } catch (Exception e) {
                Log.d(TAG, "InsertData: Error ", e);
                return new String("Error: " + e.getMessage());
            }
        }
    }
}

 

XML 코드 [ layout ] 

 

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:background="#99111111"
    tools:context=".MainActivity">

    <LinearLayout
        android:layout_width="match_parent"
        android:paddingTop="300dp"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:orientation="vertical"
        android:paddingLeft="30dp"
        android:paddingRight="30dp">

        <EditText
            android:id="@+id/ID"
            android:layout_width="300dp"
            android:layout_gravity="center"
            android:layout_height="wrap_content"
            android:layout_marginBottom="10dp"
            android:background="#B0AEE6FF"
            android:hint="ID를 입력하세요."
            android:textSize="15dp"
            android:padding="10dp"
            android:gravity="center"/>
        <EditText
            android:id="@+id/PW"
            android:layout_width="300dp"
            android:layout_gravity="center"
            android:layout_height="wrap_content"
            android:layout_marginBottom="10dp"
            android:background="#B0AEE6FF"
            android:hint="패스워드를 입력하세요."
            android:textSize="15dp"
            android:padding="10dp"
            android:gravity="center"/>
        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_gravity="center"
            android:orientation="horizontal">

            <Button
                android:id="@+id/sign_in"
                android:layout_width="100dp"
                android:layout_height="50dp"
                android:text="로그인"
                android:layout_marginRight="10dp"
                android:background="#D7C0FF"
                android:layout_marginTop="20dp"/>

            <Button
                android:id="@+id/sign_up"
                android:layout_width="100dp"
                android:layout_height="50dp"
                android:text="회원가입"
                android:layout_marginLeft="10dp"
                android:background="#D7C0FF"
                android:layout_marginTop="20dp"/>

        </LinearLayout>





    </LinearLayout>



</LinearLayout>

 

위 코드로 구현된 어플을 실행해보겠습니다.

 

아래 영상은 성공했을때의 화면입니다.

 

 

아래 영상은 실패했을때의 화면입니다.

 

 

정상적으로 동작하는 것을 확인할 수 있습니다.

 

 

검색을통해 다른분들이 만드신 여러가지 코드를 살펴보았지만, POST 방식으로 많이 구현한것을 보았습니다.

 

하지만 제가 공부하기로는 데이터를 수정 또는 삭제하는것이 아닌, 검색하는 기능에서는 GET 방식을 사용해야 한다고 알고있어 GET 방식으로 구현하였습니다.