zoukankan      html  css  js  c++  java
  • PHP+ MongoDB

    环境:

    uname -v
    #1 SMP Debian 3.2.57-3+deb7u2
    
    php -v PHP 5.4.30-1~dotdeb.1 (cli) (built: Jun 29 2014 23:18:55) Copyright (c) 1997-2014 The PHP Group Zend Engine v2.4.0, Copyright (c) 1998-2014 Zend Technologies

    安装MongoDB驱动:

    1、安装PECL(PHP 扩展模块)

    sudo apt-get install php5-dev php5-cli php-pear

    2、通过pecl安装驱动

    sudo pecl install mongo

    安装过程中有个提示,默认回车即可。

    编辑php.ini文件:

    sudo vi /etc/php5/fpm/php.ini

    在文件最后添加一行:

    extension=mongo.so

    最后重启php服务:

    sudo service php5-fpm restart 

    测试

    新建一个php文件:test.php,内容如下:

    <?php
    $user = array(
        'first_name' => 'MongoDB',
        'last_name' => 'Fan',
        'tags' => array('developer','user')
    );
    // Configuration
    $dbhost = 'localhost';
    $dbname = 'test';
    
    // Connect to test database
    $m = new Mongo("mongodb://$dbhost");
    $db = $m->$dbname;
    
    // Get the users collection
    $c_users = $db->users;
    
    // Insert this new document into the users collection
    $c_users->save($user);
    ?>

    这是在mongodb的test数据库中的users表中插入一条记录。按mongodb的说法是,在数据库test的集合users中插入一个文档。

    在浏览器中打开这个test.php页面,数据就插入到数据库中了。回到mongodb中看看是否有数据:

    mongo test
    MongoDB shell version: 2.6.3
    connecting to: test
    > db.users.findOne()
    {
        "_id" : ObjectId("53b79360b2c88865388b4567"),
        "first_name" : "MongoDB",
        "last_name" : "Fan",
        "tags" : [
            "developer",
            "user"
        ]
    }
    > 

    是的,可以看到php中的代码已经生效了。

    在php中怎么读取mongodb的数据呢?

    新建一个test2.php文件,内容如下:

    <?php
    // Configuration
    $dbhost = 'localhost';
    $dbname = 'test';
    
    // Connect to test database
    $m = new Mongo("mongodb://$dbhost");
    $db = $m->$dbname;
    
    // Get the users collection
    $c_users = $db->users;
    
    // Find the user with first_name 'MongoDB' and last_name 'Fan'
    $user = array(
        'first_name' => 'MongoDB',
        'last_name' => 'Fan'
    );
    
    $user = $c_users->findOne($user);
    var_dump($user);
    ?>

    在浏览器中打开test2.php就可以看到结果了。

  • 相关阅读:
    截图软件FastStone
    java中继承thread类的其他类的start()方法与run()方法
    .net连接MySql 出错
    题解【Codeforces1139C】Edgy Trees
    题解【Codeforces580C】Kefa and park
    题解【Codeforces1234D】Distinct Characters Queries
    题解【洛谷P4025】[PA2014]Bohater
    题解【洛谷P1445】[Violet]樱花
    题解【洛谷P2516】[HAOI2010]最长公共子序列
    题解【洛谷P3275】[SCOI2011]糖果
  • 原文地址:https://www.cnblogs.com/ibgo/p/3825787.html
Copyright © 2011-2022 走看看