티스토리 뷰
오늘은 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를 구현해보겠습니다. 😊
'MongoDB' 카테고리의 다른 글
[MongoDB] php MongoDB update / delete (0) | 2022.05.11 |
---|---|
[MongoDB] php MongoDB insert / auto increasement 구현하기 (0) | 2022.05.10 |
공지사항
최근에 올라온 글
최근에 달린 댓글
- Total
- Today
- Yesterday
링크
TAG
- input placeholder
- curl.cainfo
- JS url 파라미터
- react restful API
- php mongodb
- php mysql 랜덤 숫자
- php 게시판
- react fetch
- curl ssl 인증서 다운로드
- curl.cainfo 에러
- 자바스크립트 세션
- 자바스크립트
- 링크 공유 시 정보 수정
- fetch get post 전송
- php composer
- php rand()
- AJAX
- http 접속 시 https 리다이렉션
- 자바스크립트 url 파라미터 추출
- 카톡 링크 공유 썸네일
- JavaScript
- JS 시계 기능
- curl ssl 인증서
- JS session
- 링크 공유 시 썸네일
- html input
- HTML
- php composer 설치
- curl.cainfo 적용
- fetch post 데이터 전송
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
글 보관함