PHP封装的简单连接MongoDB类示例

yipeiwu_com7年前PHP代码库

本文实例讲述了PHP封装的简单连接MongoDB类。分享给大家供大家参考,具体如下:

1. 封装MongoDB类

<?php
class MongoDB
{
  private $database;
  private $mongo;
  function __construct()
   {
    $this->mongo = new MongoClient("mongodb://user:password@server_address:port/admin");
    $this->database = $this->mongo->selectDB("data");
  }
  {
    return $this->database->selectCollection($collection);
  }
  //获取所有的集合名
  function getCollections() 
  {
    return $this->database->getCollectionNames();
  }
  //选数据库
  function selectDB($db)
  {
    $this->database = $this->mongo->selectDB($db);
  }
}

2. 简单调用,insert数据。

class DemoController extends CI_Controller
{
  function __construct() {
    parent::__construct();
    //CI中加载类
    $this->load->library('mongo_lib', '', 'mongodb');
  }
  //插入一条数据
  function create()
  {
    $data = array('name'=>'mike','email'=>'abc@163.com);
    //选择库,shell:user demo_db
    $this->mongodb->selectDB('demo_db');
    //选择集合,db.demo_col.insert();
    $rebateCollection = $this->mongodb->getCollection('demo_collection');
    $res = $rebateCollection->insert($data);
  }
}

更多关于PHP相关内容感兴趣的读者可查看本站专题:《PHP+MongoDB数据库操作技巧大全》、《PHP基于pdo操作数据库技巧总结》、《php面向对象程序设计入门教程》、《php字符串(string)用法总结》、《php+mysql数据库操作入门教程》及《php常见数据库操作技巧汇总》

希望本文所述对大家PHP程序设计有所帮助。

相关文章

基于PHP常用字符串的总结(待续)

1.分割与合并implode:echo implode(",", array('lastname', 'email', 'phone'));//数组转成字符串explode:print_...

nginx下安装php7+php5

起步 之前在服务器搭建了lamp环境,想换用性能更强的nginx作为服务器软件,又想将php5升级为php7. 安装nginx无需赘述:sudo apt-get install ng...

PHP正则表达式匹配替换与分割功能实例浅析

本文实例讲述了PHP正则表达式匹配替换与分割功能。分享给大家供大家参考,具体如下: 正则表达式在PHP中的作用主要包括:分割、匹配、查找与替换。 匹配功能 preg_match_all...

解析php中的fopen()函数用打开文件模式说明

fopen() 函数用于在 PHP 中打开文件。此函数的第一个参数含有要打开的文件的名称,第二个参数规定了使用哪种模式来打开文件:复制代码 代码如下:<?php$file=fope...

PHP遍历某个目录下的所有文件和子文件夹的实现代码

复制代码 代码如下:<?php function read_all_dir ( $dir )    {   &...