본문 바로가기

서버/UBUNTU 18.04

[#G1] PHP를 이용해 DB[MySQL]에 데이터 저장하는 방법

해당 포스트는 XAMPP ( Apache + Php + MySQL ) 웹서버와 안드로이드 및 IOS에서의 운용을 기준으로 제작되었습니다.



PHP는 POST, GET 방식으로 데이터를 가져올 수 있습니다.


1
2
3
4
5
//METHOD 'POST'
$data = $_POST['data'];
 
//METHOD 'GET'
$data = $_GET['data'];
cs

 


먼저, 데이터를 저장할 데이터베이스를 지정하기 위해 php를 저장할 디렉터리 하위에 include 디렉터리를 만들고, Config.phpDB_Connect.php를 생성합니다.


Xampp 기준 C:\xampp\htdocs\include


1
2
3
4
5
6
7
8
9
10
11
12
//Config.php in include DIR
 
<?php
 
/**
 * Database config variables
 */
define("DB_HOST", "localhost");
define("DB_USER", "root");
define("DB_PASSWORD", "password");
define("DB_DATABASE", "myDatabase");
?>
cs


 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
//DB_Connect.php in include DIR
 
<?php
class DB_Connect {
    private $conn;
 
    // Connecting to database
    public function connect() {
        require_once 'include/Config.php';
         
        // Connecting to mysql database
        $this->conn = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_DATABASE);
         
        // return database handler
        return $this->conn;
    }
}
 
cs



마찬가지로 include 디렉터리에 DB_FUNCTION 도 추가합니다. 출처는 Ravi Tamada 입니다.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
<?php
 
/**
 * @author Ravi Tamada
 * @link https://www.androidhive.info/2012/01/android-login-and-registration-with-php-mysql-and-sqlite/ Complete tutorial
 */
 
class DB_Functions {
 
    private $conn;
 
    // constructor
    function __construct() {
        require_once 'DB_Connect.php';
        // connecting to database
        $db = new Db_Connect();
        $this->conn = $db->connect();
    }
 
    // destructor
    function __destruct() {
         
    }
 
    /**
     * Storing new user
     * returns user details
     */
 
    public function storeData($data1, $data2) {
     
        $stmt = $this->conn->prepare("INSERT INTO dataSets(data1, data2, created_at) VALUES(?, ?, NOW())");
        $stmt->bind_param("ss", $data1, $data2);
        $result = $stmt->execute();
        $stmt->close();
 
        // check for successful store
        if ($result) {
            $stmt = $this->conn->prepare("SELECT * FROM dataSets WHERE data1= ? and data2 = ?");
            $stmt->bind_param("ss", $data1, $data2);
            $stmt->execute();
            $user = $stmt->get_result()->fetch_assoc();
            $stmt->close();
 
            return $user;
        } else {
            return false;
        }}
 
    /**
     * Check user is existed or not
     */
 
    public function isDataExisted($data1, $data2) {
        $stmt = $this->conn->prepare("SELECT data1, data2 from dataSets WHERE data1 = ? and data2 = ?");
 
        $stmt->bind_param("ss", $data1, $data2);
 
        $stmt->execute();
 
        $stmt->store_result();
 
        if ($stmt->num_rows > 0) {
            // user existed 
            $stmt->close();
            return true;
        } else {
            // user not existed
            $stmt->close();
            return false;
        }}
 
 
}
 
?>
cs


이 클래스에는 2개의 Function이 있는데, storeData()isDataExisted()이며 이는 각각 데이터를 저장하고, 데이터가 DB에 존재하는지 체크하는 역할입니다.


이제 상위 디렉터리 (htdocs)에 이것을 운용할 수 있는 php를 생성하면 됩니다.


만약 GET 방식으로 데이터를 보냈다면 _POST -> _GET 으로 바꿔주면 됩니다.



SOURCE CODE


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
<?php
 
require_once 'include/DB_Functions.php';
$db = new DB_Functions();
 
// json response array
$response = array("error" => FALSE);
 
if (isset($_POST['data1']) && isset($_POST['data2'])) {
 
    // receiving the post params
    $data1 = $_POST['data1'];
    $data2 = $_POST['data2'];
 
    // check if datas are already existed in DB
    if ($db->isUserExisted($data1$data2)) {
 
        // user already existed
        $response["error"= TRUE;
        $response["error_msg"= "datas already existed";
        echo json_encode($response);
 
    } else {
 
        //store datas
        $user = $db->storeUser($data1$data2);
 
        if ($user) {
            // stored successfully
            $response["error"= FALSE;
            $response["user"]["uid"= $user["uid"];
            $response["user"]["email"= $user["email"];
            echo json_encode($response);
        } else {
            // failed to store
            $response["error"= TRUE;
            $response["error_msg"= "ERROR : (MYSQL ERROR)";
            echo json_encode($response);
        }
 
    }
 
else {
 
    $response["error"= TRUE;
    $response["error_msg"= "ERROR : (REQUIRED DATA MISSING)";
    echo json_encode($response);
 
}
?>
cs


'서버 > UBUNTU 18.04' 카테고리의 다른 글

HTTP to HTTPS  (0) 2021.05.19