dota220141003 2014-07-15 23:13
浏览 66
已采纳

在NetBeans中使用Slim Framework将Php连接到MongoDB

I just downloaded and installed Slim to my Php Project and I have been trying to use it to connect to a MongoDB that I have. I know how to connect it to mysql and I saw numerous examples online, but I do not know how to connect it to mongodb. I did it through php without slim and it worked fine and I could query data, so I'm trying to do the same thing using Slim. Any help would be appreciated.

  • 写回答

1条回答 默认 最新

  • doujing8435 2014-07-16 07:09
    关注
    Try this code:
    <?php
    
    require 'Slim/Slim.php';
    
    $app = new Slim();
    
    $app->get('/listdata', 'showData');
    $app->post('/create', 'addData');
    $app->run();
    
    function addData()
    {
    // connect
        $m = new MongoClient();
    // select your database
        $db = $m->dbname;
    // select your collection
        $collection = $db->collectionname;
    // add a record
        $document = array("title" => "title 1", "author" => "author 1");
        $collection->insert($document);
    // add another record
        $document = array("title" => "title 2", "author" => "author 2");
        $collection->insert($document);
    }
    
    function showData()
    {
    // connect
        $m = new MongoClient();
    // select your database
        $db = $m->dbname;
    // select your collection
        $collection = $db->collectionname;
    // find everything in the collection
        $cursor = $collection->find();
    // Show the result here
        foreach ($cursor as $document) {
            echo $document["title"] . "
    ";
        }
    }
    
    ?>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 关于Ubuntu20.04.3LTS遇到的问题:在安装完CUDA驱动后,电脑会进入卡死的情况,但可以通过键盘按键进入安全重启,但重启完又会进入该情况!
  • ¥15 关于#嵌入式硬件#的问题:树莓派第一天重装配置python和opencv后第二天打开就成这样,瞎捣鼓搞出来文件夹还是没把原来的界面调回来
  • ¥20 Arduino 循迹小车程序电路出错故障求解
  • ¥20 Arduino 循迹小车程序电路出错故障求解
  • ¥100 AT89C52单片机C语言调试之后再回答
  • ¥15 AT89C52单片机C语言串口助手发送数据包返回值
  • ¥15 C++数组中找第二小的数字程序纠错
  • ¥15 wannier复现图像时berry曲率极值点与高对称点严重偏移
  • ¥15 利用决策森林为什么会出现这样·的问题(关键词-情感分析)
  • ¥15 DispatcherServlet.noHandlerFound No mapping found for HTTP request with URI[/untitled30_war_e