티스토리 뷰

아래의 블로그를 보고 참고하여 만들었습니다.

 

https://webnautes.tistory.com/828

 

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

 

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

 

 

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

 

 

https://nickjoit.tistory.com/144

 

또한 과정을 진행하려면, 외부 IP에서 MySql에 들어올 수 있도록 권한 설정이 된 아이디를 사용해야 합니다!

 

 

php 코드

 

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

 

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'];
        $phone=$_POST['phone'];


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

        else if(empty($phone)){
            $errMSG = "폰번호를입력하세요.";
        }

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


                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" />
                phone: <input type = "text" name = "phone" />
                <input type = "submit" name = "submit" />
            </form>
       
       </body>
    </html>

<?php 
    }
?>

 

dbcon.php

 

<?php

    $host = '192.168.0.140'; #라즈베리가 연결된 아이피
    $username = 'admin'; # MySQL 계정 아이디
    $password = 'admin'; # MySQL 계정 패스워드
    $dbname = 'db';  # 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/insert.php 에 접속하시면

(ex 192.168.0.140/insert.php)

 

 

 

 

이런 화면이 나옵니다.

 

여기에 

 

 

각각 데이터를 입력하고 제출을 누르면

 

 

 

 

 

 

 

 

db에 방금 넣은 데이터가 들어간 것을 볼 수 있습니다.

 

 

참고로  db관련 작업은 apt-get install phpMyAdmin 명령어를 통해

 

phpMyAdmin 을 설치하여 작업하였습니다.

 

여기 접속하는방법은 라즈베리 ip/phpMyAdmin 을 주소창에 검색하면 됩니다.

 

(ex 192.168.0.140/phpMyAdmin , 주의 : 대소문자 구분 필요)

 

 

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

 

 

 

 

android java 코드

package com.example.um;

import android.app.ProgressDialog;
import android.content.Intent;
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 android.widget.Toast;

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 user_signupActivity extends AppCompatActivity {

    private static String IP_ADDRESS = "192.168.0.140";
    private static String TAG = "phptest";

    private EditText mEditTextName;
    private EditText mEditTextCountry, mEditTextphone;
    private TextView mTextViewResult;

    String name;

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

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


        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();
                String phone = mEditTextphone.getText().toString();

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

                name = mEditTextName.getText().toString();
                mEditTextName.setText("");
                mEditTextCountry.setText("");
                mEditTextphone.setText("");

                Toast.makeText(getApplicationContext(), "id : "+name +" 님의 회원가입이 완료 되었습니다.", Toast.LENGTH_LONG).show();

                Intent intent = new Intent(user_signupActivity.this, MainActivity.class);
                startActivity(intent);

            }
        });

    }



    class InsertData extends AsyncTask<String, Void, String>{
        ProgressDialog progressDialog;

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

            progressDialog = ProgressDialog.show(user_signupActivity.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 phone = (String)params[3];

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


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

        }
    }


}


안드로이드 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="user_id"
        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:id="@+id/textView_main_country"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Password" />

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

    <TextView
        android:id="@+id/textView_phone"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="User_Phone" />

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

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

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

</LinearLayout>

 

메인엑티비티는 따로 꾸몄기때문에 회원가입하는 창만 참고하시면 되겠습니다.

 

코드는 회원가입 버튼을 누르면 메인으로 다시 돌아가게 만들어 두었습니다.

 

원래는 비밀번호 확인, 약관동의 등을 해야하지만 테스트 코드이므로 간단한 예제로 만들었습니다.

 

 

여기에 각각 데이터를 넣은 후 SIGN_UP 버튼을 클릭하면,

 

 

 

 

 

 

MySql에 데이터가 추가된 것을 볼 수 있습니다.

 

 

 

 

데이터가 PHP페이지를 거쳐 DB에 저장되게 됩니다.

 

 

2020/12/09 - [인턴/웹] - Android PHP MySQL 로그인 예제 [GET 방식] , HTTP REST API

 

Android PHP MySQL 로그인 예제 [GET 방식] , HTTP REST API

2020/06/30 - [인턴/웹] - Android PHP MySQL 회원가입 예제 - 데이터베이스에 값 입력하기 Android PHP MySQL 회원가입 예제 - 데이터베이스에 값 입력하기 아래의 블로그를 보고 참고하여 만들었습니다. https:/

15051015.tistory.com

 

댓글
최근에 올라온 글
최근에 달린 댓글
250x250