티스토리 뷰

오늘은 php에서 MongoDB를 연동하고 Ajax를 사용한 CRUD 중 R (Read)에 해당하는 select를 구현해보겠습니다.

저는 Robo 3T를 사용하고, 다음과 같은 DB를 구축해두었습니다.

 

 

우선 몽고디비와 연동해보겠습니다.

 

mongo.php

<?php
    try {
        $con = new MongoDB\Driver\Manager('mongodb://localhost:27017');
    }
    catch (MongoException $e){
        echo "error message: ".$e->getMessage();
    }
    
    header('Content-Type: application/json');
    header("Content-Type: text/html;charset=utf-8");
?>

현재 로컬에서 작업 진행중이므로 localhost로 연결했는데요, 만약 비밀번호가 있는 경우라면 다음과 같이 하시면 됩니다.

$con = new MongoDB\Driver\Manager("mongodb://아이디:비밀번호@ip주소:포트번호/접속대상");

db와 연동이 잘 되었는지 확인하려면 var_dump를 사용해 확인할 수 있습니다.

var_dump($con);

db와 연동이 잘 되었다면 select를 구현해보겠습니다.

 

select.php

<?php
    include("mongo.php");

    // *select*

    $filter = []; //필터없으면 전체 선택
    // $filter = ['title' => "title03"]; //조건에 해당할 때만 가져오기

    $options= [];
    //option은 개수 제한 / 정렬 필요시 추가
    // $options = ['limit'=>2]; //최대 2개만 가져오기
    // $options = ['sort'=>array('_id'=>-1)]; //내림차순

    $query = new MongoDB\Driver\query($filter,$options);
    // $query = new MongoDB\Driver\query([]); //조건없이 전체조회


    $rows = $con->executeQuery("db00.topic", $query);
    
    $data=[];
    foreach($rows as $row){
        array_push($data,[
            "num" => $row -> num,
            "title" => $row -> title,
            "content" => $row -> content 
        ]);
    }

    echo json_encode($data);
?>

데이터를 가져오는 코드를 작성했다면 데이터를 보여주는 페이지를 만들어 보겠습니다.

 

index.php (Ajax 포함)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>INDEX</title>
    <style>
        table{
            border-collapse: collapse;
        }
        table tr td{
            border: 1px solid #ccc;
        }
    </style>
</head>
<body>
    <table>
        <tr>
            <td>index</td>
            <td>title</td>
            <td>content</td>
            <td>delete</td>
            <td>update</td>
        </tr>
    </table>    
</body>

<script src="jquery.min.js"></script>
<script>
    function select(){
        $.ajax({
            type: 'POST',
            dataType: 'json',
            url: 'select.php',
            data: {},
            success: function(data){

                for(var i in data){
                    $("table").append("<tr><td>"+data[i].num+"</td><td>"+data[i].title+"</td><td>"+data[i].content+"</td><td id='delete' onclick='delete_(this)'>삭제</td><td id='update' onclick='beforeUpdate(this)'>수정</td></tr>");
                }

            }
        })
    }
    select();
</script>
</html>

Ajax로 데이터를 가져와 페이지에 넣어주는데요, 결과입니다.

데이터를 잘 가져왔습니다! 다음 포스팅에서는 insert, update, delete를 구현해보겠습니다. 😊