반응형



안드로이드 앱이  PHP 프로그램을 매개로 하여 MySQL 데이터베이스 서버에 데이터를 저장하는 간단한 예제입니다. 

 


1. Apache2, MySQL, PHP7 설치
2. 데이터베이스 및 테이블 생성
3. 웹브라우저로 PHP 동작  테스트
4. Android 앱에서 테스트
5. 코드 설명
6. 관련 포스팅
7. 참고

 

2015. 11. 21 최초 작성 

2019. 11. 17 androidx 사용하도록 변경

2020.  7. 14  MySQL을 디폴트로 바꾸는 방법 추가 



안드로이드 앱에서 바로 MySQL에 접속한다면 구현이 간단할 수 있습니다.

하지만 리버스 엔지니어링을 통해 안드로이드 앱에서 소스코드를 추출하게 되면 서버 아이피와 MySQL 서버 접속용 아이디와 패스워드가 유출될 수 있습니다. 

 

그래서 웹서버에서 실행되는 PHP를 이용하여 진행하게 됩니다.  안드로이드 앱의 코드를 추출한다 해도 서버 IP와 실행되는 PHP 파일 이름만 알 수 있습니다. 

하지만 해당 IP와 PHP 파일에 대한 정보를 통해 악용할 수도 있기 때문에 추가로 필요한 작업이 있을 수도 있을 듯하지만 제가 아는 범위에서 벗어나서 논외로 합니다. 

 



Amazon AWS를 사용하여 구현한 예제입니다.

 

AWS Rest API를 Android와 연동해보기( Lambda + API Gateway + DynamoDB )

https://webnautes.tistory.com/1590

 

1. Apache2, MySQL, PHP7 설치

서버로 사용하려는 운영체제에 따라 1-1 또는 1-2를 진행하세요.

1-1. WIndows

다음 포스팅을 참고하여 윈도우에 WAMP( Apache2, MySQL , PHP7)를 설치합니다. 

 


윈도우 기반 웹 개발 환경 만들기 ( Apache2, PHP, MySQL, PhpMyAdmin )
http://webnautes.tistory.com/1206 



오른쪽 아래 시계 옆에 있는 WampServer 트레이 아이콘을 마우스 왼쪽 버튼으로 클릭한 후, 메뉴에서 PHP > Version을 선택합니다. 

 

사용가능한 PHP 버전이 보이는 데 최신 버전인 7.2.18를 선택합니다. 글 작성시점과 버전이 다를 수 있습니다. 

 




1-2. Ubuntu

다음 포스팅을 참고하여 Ubuntu에  LAMP( Apache2, MySQL , PHP7)를 설치합니다. 

 


Ubuntu 18.04에 LAMP ( Apache2, MySQL , PHP7) 설치하는 방법
http://webnautes.tistory.com/1185    




2. 데이터베이스 및 테이블 생성 

 

2-1. MySQL에서 데이터베이스를 새로 생성하고  해당 데이베이스를 접근할 수 있는 사용자를 추가하는 방법을 설명합니다. 

 

서버 컴퓨터의 운영체제가 Windows라면 2-2, Ubuntu라면 2-3을 진행하세요.




2-2. 오른쪽 아래 시계 옆에 있는 WampServer 트레이 아이콘을 마우스 왼쪽 버튼으로 클릭한 후, 메뉴에서 MySQL > MySQL console을 선택합니다. 

 

로그인 사용자로 root가 지정되어 있습니다. OK 버튼을 클릭합니다. 

 



Enter password: 라는 메시지가 보입니다.  설치시 설정해주었던 root 암호를 입력해주면 로그인이 완료됩니다. 

 

root 암호를 설정한 적이 없다면 엔터를 입력하여 진행할 수도 있지만 포스팅의 1-1을 다시 진행하여 root 암호를 부여해주세요.. 

 

 

이제 2-4를 진행하세요.




2-3. Ubuntu 18.04에서 설치한 MySQL에서는 디폴트로 auth_socket 플러그인을 사용하기 때문에 기존에 사용하던 방법(root 계정의 암호입력)으로 로그인이 되지 않습니다. 

 

확인을 못해봤는데 Ubuntu 16.04에서 최신 버전 MySQL을 사용한다면 같은 상황이 있을 수 있습니다. 

 

webnautes@webnautes-pc:~$ mysql -u root -p
Enter password:
ERROR 1698 (28000): Access denied for user 'root'@'localhost'



sudo 명령시 입력하는 사용자 암호 입력으로 기존 로그인을 대체합니다.

 

webnautes@webnautes-pc:~$ sudo mysql
[sudo] webnautes의 암호:
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 14
Server version: 5.7.22-0ubuntu18.04.1 (Ubuntu)

Copyright (c) 2000, 2018, Oracle and/or its affiliates. All rights reserved.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.


mysql>




2-4. 윈도우와 우분투에서 동일하게 진행하는 부분입니다.

 

데이터베이스를 생성합니다. 

 

mysql> create database 데이터베이스이름 DEFAULT CHARSET=utf8 COLLATE=utf8_general_ci;

 

mysql> create database testdb default character set utf8;
Query OK, 1 row affected (0.00 sec)



새로 생성한 데이터베이스를 사용할 사용자를 생성합니다. 

 

mysql> create user 사용자이름 identified by '패스워드';

 

mysql> create user webnautes identified by 'apple9!';
Query OK, 0 rows affected (0.01 sec)



앞에서 생성했던 데이터베이스를 새로 생성한 사용자가 사용하도록 권한을 부여합니다.  

 

mysql> GRANT ALL PRIVILEGES ON 데이터베이스이름.* TO '사용자이름'@'localhost' identified by '패스워드';

 

mysql> grant all privileges on testdb.* to 'webnautes'@'localhost' identified by 'apple9!';
Query OK, 0 rows affected, 1 warning (0.00 sec)



quit를 입력하여 MySQL 콘솔을 종료합니다.




2-5.  MySQL 콘솔에 새로 생성한 사용자로 접속합니다. 

 

우분투에서는 다음처럼 MySQL 로그인을 합니다. 사용자 이름은 새로 생성한 데이터베이스 접근권한을 가진 사용자 입니다. 

Enter password: 에 사용자의 암호를 입력해줍니다. 

 

$ mysql -u 사용자이름 -p
Enter password:



윈도우에서는 오른쪽 아래 시계 옆에 있는 WampServer 트레이 아이콘을 마우스 왼쪽 버튼으로 클릭한 후, 메뉴에서 MySQL > MySQL console을 선택합니다.

 

새로 생성한 데이터베이스 접근권한을 가진 사용자 이름을 적고 OK 버튼을 클릭합니다. 

 



Enter password: 메시지가 보이면 사용자의 암호를 입력해줍니다. 

 

Enter password:




2-6. 데이터베이스 testdb에 필요한 테이블 person을 생성하고  MySQL이 잘 동작하는지 여부를 다음처럼 확인합니다. 

 

앞에서 생성해두었던 데이터베이스 testdb가 보입니다.


mysql> show databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| testdb             |
+--------------------+
2 rows in set (0.00 sec)


데이터베이스 testdb를 사용하도록 하고

mysql> use testdb;
Database changed



다음 명령을 복사 후 붙여넣기 해서 person 테이블을 생성합니다.

create table person(
      id bigint(20) unsigned not null auto_increment,
      name varchar(255) not null,
      country varchar(255) not null,
      primary key (id)
)  DEFAULT CHARSET=utf8 COLLATE=utf8_general_ci;


mysql> create table person(
    ->      id bigint(20) unsigned not null auto_increment,
    ->      name varchar(255) not null,
    ->      country varchar(255) not null,
    ->      primary key (id)
    -> )  DEFAULT CHARSET=utf8 COLLATE=utf8_general_ci;
Query OK, 0 rows affected (0.03 sec)


person 테이블이 생성되었습니다.


mysql> show tables;
+--------------+
| Tables_in_db |
+--------------+
| person       |
+--------------+
1 row in set (0.00 sec)



데이터 하나를 테이블에 입력 해봅니다. 


mysql> insert into person(name, country) values('test', 'test');
Query OK, 1 row affected (0.00 sec)


쿼리를 해서 데이터를 다시 가져와 봅니다.

 
mysql> select * from person;
+----+------+---------+
| id | name | country |
+----+------+---------+
|  1 | test | test    |
+----+------+---------+
1 row in set (0.00 sec)


person 테이블의 데이터를 초기화합니다. 


mysql> truncate person;
Query OK, 0 rows affected (0.01 sec)



테이블이 초기화 되었습니다.

mysql> select * from person;

Empty set (0.00 sec)



MySQL 콘솔을 종료합니다.

mysql> exit
Bye




3. 웹브라우저로 PHP 동작  테스트

Android 앱으로 테스트를  진행하기 전에 다음 PHP 코드를  웹 브라우저로 간단한 테스트를 해보겠습니다.

 

다음 두 개의 파일이 필요합니다.

dbcon.php

MySQL 서버 접속을 위해 사용되는 코드입니다. 

 

insert.php

지정해 높은 데이터베이스의 테이블에 데이터를 저장하기 위해 사용됩니다.



dbcon.php

 

<?php

    $host = 'localhost';
    $username = 'webnautes'; # MySQL 계정 아이디
    $password = 'apple9!'; # 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();
?>




insert.php

 

<?php

    error_reporting(E_ALL);
    ini_set('display_errors',1);

    include('dbcon.php');


    if( ($_SERVER['REQUEST_METHOD'] == 'POST') && isset($_POST['submit']))
    {

        $name=$_POST['name'];
        $country=$_POST['country'];

        if(empty($name)){
            $errMSG = "이름을 입력하세요.";
        }
        else if(empty($country)){
            $errMSG = "나라를 입력하세요.";
        }

        if(!isset($errMSG))
        {
            try{
                $stmt = $con->prepare('INSERT INTO person(name, country) VALUES(:name, :country)');
                $stmt->bindParam(':name', $name);
                $stmt->bindParam(':country', $country);

                if($stmt->execute())
                {
                    $successMSG = "새로운 사용자를 추가했습니다.";
                }
                else
                {
                    $errMSG = "사용자 추가 에러";
                }

            } catch(PDOException $e) {
                die("Database error: " . $e->getMessage());
            }
        }

    }
?>

<html>
  <body>
        <?php
        if (isset($errMSG)) echo $errMSG;
        if (isset($successMSG)) echo $successMSG;
        ?>
       
        <form action="<?php $_PHP_SELF ?>" method="POST">
            Name: <input type = "text" name = "name" />
            Country: <input type = "text" name = "country" />
            <input type = "submit" name = "submit" />
        </form>
 
  </body>
</html>




3-1. 윈도우라면 C:\wamp64\www\ 경로에 파일을 생성합니다.



3-2. 우분투라면 /var/www/html/ 경로에 파일을 생성합니다.



3-3. 웹브라우저에서  localhost/insert.php 주소로 접속하면 아래와 같은 화면이 보이게 됩니다. 

 




최근에 나온(2020. 7. 14 기준)  WampServer의 경우 프로그램 설치시 MySQL를 선택해야 설치되며  디폴트 데이터베이스가 아래 스크린샷처럼 MariaDB로 되어 있습니다. 

WampServer 트레이 아이콘에서 왼쪽 버튼으로 클릭하면 보입니다. 

 

MySQL을 디폴트로 변경하지 않으면 다음과 같은 에러가 날 수 있습니다. 

얼마전 이 에러를 질문하신분이 있었는데 이런 문제가 있는줄 몰랐네요..

 

Failed to connect to the database: SQLSTATE[HY000] [1045] Access denied for user 'webnautes'@'localhost' (using password: YES) 

 




WampServer 트레이아이콘에서 마우스 오른쪽 버튼을 눌러  보이는 메뉴에서 Tools > Invert default DBMS MariaDB <-> MySQL을 선택합니다. 

디폴트 DBMS가 MariaDB에서 MySQL으로 변경되게 됩니다. 

 

 

다음처럼 MySQL이 디폴트로 바뀌어야 합니다. 

 




정상적으로 테이블에 데이터가 입력되면 출력되는 메시지입니다.

 



이름이나 나라를 입력하지 않으면 에러 메시지를 출력하도록 되어 있습니다.

 

 




3-4. 안드로이드 폰의 웹브라우저에서도 테스트해 봅니다.

 



접속에 문제가 있다면 다음 포스트 16번부터  참고하세요.

 


윈도우 기반 웹 개발 환경 만들기 ( Apache2, PHP, MySQL, PhpMyAdmin )
 http://webnautes.tistory.com/1206 




3-5. MySQL에서 확인해보면 데이터가 정상적으로 입력된 것을 볼 수 있습니다. 

 

SELECT 문으로 testdb 데이터베이스에 있는 Person 테이블의 내용을 조회합니다.

웹에서 입력한 이름과 주소가 제대로 입력되었는지 확인가능합니다.

 




4. Android 앱에서 테스트

 

웹서버의 PHP 파일을 통해 데이터베이스에 데이터를 저장하는 안드로이드 앱을 작성합니다.



4-1. insert.php 파일을 다음 코드로 변경합니다. 

 

<?php

    error_reporting(E_ALL);
    ini_set('display_errors',1);

    include('dbcon.php');


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


    if( (($_SERVER['REQUEST_METHOD'] == 'POST') && isset($_POST['submit'])) || $android )
    {

        // 안드로이드 코드의 postParameters 변수에 적어준 이름을 가지고 값을 전달 받습니다.

        $name=$_POST['name'];
        $country=$_POST['country'];

        if(empty($name)){
            $errMSG = "이름을 입력하세요.";
        }
        else if(empty($country)){
            $errMSG = "나라를 입력하세요.";
        }

        if(!isset($errMSG)) // 이름과 나라 모두 입력이 되었다면
        {
            try{
                // SQL문을 실행하여 데이터를 MySQL 서버의 person 테이블에 저장합니다.
                $stmt = $con->prepare('INSERT INTO person(name, country) VALUES(:name, :country)');
                $stmt->bindParam(':name', $name);
                $stmt->bindParam(':country', $country);

                if($stmt->execute())
                {
                    $successMSG = "새로운 사용자를 추가했습니다.";
                }
                else
                {
                    $errMSG = "사용자 추가 에러";
                }

            } catch(PDOException $e) {
                die("Database error: " . $e->getMessage());
            }
        }

    }

?>


<?php
    if (isset($errMSG)) echo $errMSG;
    if (isset($successMSG)) echo $successMSG;

$android = strpos($_SERVER['HTTP_USER_AGENT'], "Android");
 
    if( !$android )
    {
?>
    <html>
      <body>

            <form action="<?php $_PHP_SELF ?>" method="POST">
                Name: <input type = "text" name = "name" />
                Country: <input type = "text" name = "country" />
                <input type = "submit" name = "submit" />
            </form>
     
      </body>
    </html>

<?php
    }
?>




4-2. AndroidManifest.xml 매니페스트 파일의  manifest 태그 하위 항목으로 인터넷 접근 허용 퍼미션을 추가합니다.

android 9.0  이상에서 동작하게 하려면 usesCleartextTraffic 옵션도 추가해야 합니다. 해주지 않으면 “cleartext http traffic to not permitted” 라는 에러가 발생합니다.  

 

 

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.tistory.webnautes.phptest">

    <uses-permission android:name="android.permission.INTERNET" />

    <application
        android:usesCleartextTraffic="true"
        android:allowBackup="true"

 

 

 

4-3. activity_main.xml 레이아웃 파일을 아래 내용으로 바꿉니다. 

 

 

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

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Name"
        android:id="@+id/textView_main_name" />

    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/editText_main_name" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Country"
        android:id="@+id/textView_main_country" />

    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/editText_main_country" />

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Insert"
        android:id="@+id/button_main_insert" />

    <TextView
        android:layout_width="match_parent"
        android:layout_height="250dp"
        android:id="@+id/textView_main_result" />

</LinearLayout>




4-4. MainActivity.java 자바 파일을 아래 내용으로 바꿉니다.

 

 

다음 줄에 있는 IP 주소를 아파치 웹서버가 설치된  컴퓨터의 IP로 수정하세요.

private static String IP_ADDRESS = "IP주소";

 

안드로이드 에뮬레이터와 서버가 같은 컴퓨터에 동작하는 경우에는 다음 아이피를 입력합니다.

Android Studio의 에뮬레이터  - 10.0.2.2

GenyMotion - 192.168.56.1  

 

package com.tistory.webnautes.phptest;

import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import android.text.method.ScrollingMovementMethod;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import java.io.BufferedReader;

import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;

import java.net.HttpURLConnection;
import java.net.URL;


public class MainActivity extends AppCompatActivity {

    private static String IP_ADDRESS = "IP주소";
    private static String TAG = "phptest";

    private EditText mEditTextName;
    private EditText mEditTextCountry;
    private TextView mTextViewResult;


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

        mEditTextName = (EditText)findViewById(R.id.editText_main_name);
        mEditTextCountry = (EditText)findViewById(R.id.editText_main_country);
        mTextViewResult = (TextView)findViewById(R.id.textView_main_result);

        mTextViewResult.setMovementMethod(new ScrollingMovementMethod());


        Button buttonInsert = (Button)findViewById(R.id.button_main_insert);
        buttonInsert.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                String name = mEditTextName.getText().toString();
                String country = mEditTextCountry.getText().toString();

                InsertData task = new InsertData();
                task.execute("http://" + IP_ADDRESS + "/insert.php", name,country);


                mEditTextName.setText("");
                mEditTextCountry.setText("");

            }
        });

    }



    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);

            progressDialog.dismiss();
            mTextViewResult.setText(result);
            Log.d(TAG, "POST response  - " + result);
        }


        @Override
        protected String doInBackground(String... params) {

            String name = (String)params[1];
            String country = (String)params[2];

            String serverURL = (String)params[0];
            String postParameters = "name=" + name + "&country=" + country;


            try {

                URL url = new URL(serverURL);
                HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();


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


                OutputStream outputStream = httpURLConnection.getOutputStream();
                outputStream.write(postParameters.getBytes("UTF-8"));
                outputStream.flush();
                outputStream.close();


                int responseStatusCode = httpURLConnection.getResponseCode();
                Log.d(TAG, "POST 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());
            }

        }
    }


}




4-5.  안드로이드 프로젝트를 빌드하여 앱을 테스트할 디바이스 또는 에뮬레이터에 설치합니다.

앱을 실행시키면 다음과 같은 화면이 보입니다.

 



테스트 문자열을 입력하고  INSERT를 터치합니다. 

 



성공한 경우 SQL문 처리 성공이라는 메시지가 보이게 됩니다.

 



Error: connect timed out 메시지가 보인다면 본 포스트의 3-4를 다시 확인해보세요.

방어벽 문제 일 수 있습니다. 




4-6. MySQL에서 확인해보면 정상적으로 입력된 것을 볼 수 있습니다.

 




5. 코드 설명

다음 두 단계를 거쳐서 안드로이드 앱의 데이터가 MySQL 서버에 저장됩니다. 

 

  1. 안드로이드 앱에서 POST 방식으로 PHP 코드에 데이터를 전달합니다. 
  2. PHP 코드에서 MySQL 서버에 접속하여 전달받은 데이터를 저장합니다.



우선 안드로이드 앱 코드를 살펴보겠습니다. 

 

@Override
protected String doInBackground(String... params) {

String name = (String)params[1];
String country = (String)params[2];



      // 1. PHP 파일을 실행시킬 수 있는 주소와 전송할 데이터를 준비합니다.
      // POST 방식으로 데이터 전달시에는 데이터가 주소에 직접 입력되지 않습니다.
String serverURL = (String)params[0];



      // HTTP 메시지 본문에 포함되어 전송되기 때문에 따로 데이터를 준비해야 합니다. 
      // 전송할 데이터는 “이름=값” 형식이며 여러 개를 보내야 할 경우에는 항목 사이에 &를 추가합니다.     
      // 여기에 적어준 이름을 나중에 PHP에서 사용하여 값을 얻게 됩니다.
      String postParameters = "name=" + name + "&country=" + country;


try {
            // 2. HttpURLConnection 클래스를 사용하여 POST 방식으로 데이터를 전송합니다.
URL url = new URL(serverURL); // 주소가 저장된 변수를 이곳에 입력합니다. 


            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();

httpURLConnection.setReadTimeout(5000); //5초안에 응답이 오지 않으면 예외가 발생합니다.

httpURLConnection.setConnectTimeout(5000); //5초안에 연결이 안되면 예외가 발생합니다.

httpURLConnection.setRequestMethod("POST"); //요청 방식을 POST로 합니다.
httpURLConnection.connect();


OutputStream outputStream = httpURLConnection.getOutputStream();
outputStream.write(postParameters.getBytes("UTF-8")); //전송할 데이터가 저장된 변수를 이곳에 입력합니다. 인코딩을 고려해줘야 합니다.

outputStream.flush();
outputStream.close();



            // 3. 응답을 읽습니다.   

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

InputStream inputStream;
if(responseStatusCode == HttpURLConnection.HTTP_OK) {

                  // 정상적인 응답 데이터
inputStream = httpURLConnection.getInputStream();
}
else{

                  // 에러 발생 
inputStream = httpURLConnection.getErrorStream();
}



            // 4. StringBuilder를 사용하여 수신되는 데이터를 저장합니다.
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();

            

            // 5. 저장된 데이터를 스트링으로 변환하여 리턴합니다.
return sb.toString();


} catch (Exception e) {

Log.d(TAG, "InsertData: Error ", e);

return new String("Error: " + e.getMessage());
}

}




PHP 코드를 보겠습니다. 

 

        // 1. 안드로이드 코드의 postParameters 변수에 적어준 이름을 가지고 값을 전달 받습니다.
        $name=$_POST['name'];
        $country=$_POST['country'];


    
        // 2. 입력안된 항목이 있을 경우 에러 메시지를 생성합니다.
        if(empty($name)){
            $errMSG = "이름을 입력하세요.";
        }
        else if(empty($country)){
            $errMSG = "나라를 입력하세요.";
        }


        // 3. 에러 메시지가 정의안되어 있다면 이름과 나라 모두 입력된 경우입니다. 
        if(!isset($errMSG))
        {
            try{
               // 4. SQL문을 실행하여 데이터를 MySQL 서버의 person 테이블에 저장합니다.
                $stmt = $con->prepare('INSERT INTO person(name, country) VALUES(:name, :country)');
                $stmt->bindParam(':name', $name);
                $stmt->bindParam(':country', $country);


                // 5. SQL 실행 결과를 위한 메시지를 생성합니다.
                if($stmt->execute())
                {
                    $successMSG = "새로운 사용자를 추가했습니다.";
                }
                else
                {
                    $errMSG = "사용자 추가 에러";
                }



6. 관련 포스팅

 


Android PHP MySQL 예제 - 데이터베이스에서 데이터를 JSON 형식으로 가져오기
http://webnautes.tistory.com/829

Android PHP MySQL 예제 - 데이터베이스 질의(query) 결과 출력하기
https://webnautes.tistory.com/1159

Android PHP MySQL 예제  - 데이터베이스에 데이터 저장 및 JSON 형식으로 가져오는 예제 프로젝트
http://webnautes.tistory.com/1189  




7. 참고

 

[1]  http://www.simplifiedcoding.net/php-android-tutorial-part-1/ 

 

[2]  http://www.simplifiedcoding.net/android-login-and-registration-with-php-mysql/ 

 

[3]  http://www.tutorialspoint.com/android/android_php_mysql.htm 

 



반응형

문제 발생시 지나치지 마시고 댓글 남겨주시면 가능한 빨리 답장드립니다.

도움이 되셨다면 토스아이디로 후원해주세요.
https://toss.me/momo2024


제가 쓴 책도 한번 검토해보세요 ^^

+ Recent posts