티스토리 뷰
프로젝트 중 CI와 MongoDB를 사용해야 할 일이 생겼는데 구글링 해 본 결과, 자료가 생각보다 많지 않았습니다.
특히 구글에 올라와 있는 대부분의 코드를 적용시켜도 구현이 안되었는데 마지막으로 시도한 코드가 working 했습니다!
저는 php 7.2, CI3 버전을 사용하고 있고, 윈도우 기반입니다.
파일 위치
application/config/mongodb.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
$config['host'] = 'DB IP주소';
$config['port'] = 포트번호;
$config['username'] = '유저이름';
$config['password'] = '비밀번호';
$config['database'] = '테이블명';
?>
application/libraries/mongodb.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class MongoDB {
private $conn;
function __construct() {
$this->ci =& get_instance();
$this->ci->load->config('mongodb');
$host = $this->ci->config->item('host');
$port = $this->ci->config->item('port');
$username = $this->ci->config->item('username');
$password = $this->ci->config->item('password');
$database = $this->ci->config->item('database');
try {
$this->ci->conn = new MongoDB\Driver\Manager('mongodb://' . $username . ':' . $password . '@' . $host. ':' . $port . '/' .$database);
} catch(MongoDB\Driver\Exception\MongoConnectionException $ex) {
show_error('Couldn\'t connect to mongodb: ' . $ex->getMessage(), 500);
}
}
function getConn() {
return $this->ci->conn;
}
}
이렇게 두 개의 파일을 생성해주신 다음 model로 이동해보겠습니다!
application/models/Mongo_model.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Mongo_model extends CI_Model{
private $conn;
function __construct()
{
parent::__construct();
$this->load->library('mongodb');
$this->conn = $this->mongodb->getConn(); //DB연결
}
function getData()
{
//데이터 받아오는 쿼리 executeQeury 후 return
}
}
?>
application/views/mongo_controller.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Mongo_controller extends CI_Controller {
public function __construct()
{
parent::__construct();
$this->load->model('Mongo_model');
}
public function index()
{
$data = $this->Mongo_model->getData();
print_r($data); //데이터를 가져왔는지 테스트
}
}
따라서 파일을 추가하면 MongoDB와 연동도 잘되고 데이터도 잘 가져와집니다!
'Codeigniter' 카테고리의 다른 글
| [Codeigniter] routes 설정 url 변경하기 (0) | 2022.04.18 |
|---|---|
| [Codeigniter] alert helper 추가하기 (0) | 2022.04.16 |
공지사항
최근에 올라온 글
최근에 달린 댓글
- Total
- Today
- Yesterday
링크
TAG
- php composer
- react restful API
- fetch post 데이터 전송
- HTML
- 자바스크립트 세션
- 링크 공유 시 정보 수정
- php mysql 랜덤 숫자
- 자바스크립트 url 파라미터 추출
- php mongodb
- 자바스크립트
- JS 시계 기능
- curl.cainfo
- curl ssl 인증서
- php composer 설치
- php 게시판
- html input
- input placeholder
- AJAX
- http 접속 시 https 리다이렉션
- 카톡 링크 공유 썸네일
- php rand()
- curl.cainfo 에러
- JS url 파라미터
- curl.cainfo 적용
- curl ssl 인증서 다운로드
- 링크 공유 시 썸네일
- JavaScript
- JS session
- react fetch
- fetch get 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 |
글 보관함