我刚刚下载 Slim 并将其安装到我的 Php 项目中,我一直在尝试使用它连接到我拥有的 MongoDB。我知道如何连接到mysql,网上看了很多例子,但我不知道如何连接到mongodb。我在没有 slim 的情况下通过 php 完成了它并且工作正常并且我可以查询数据,所以我正在尝试使用 Slim 做同样的事情。任何帮助将不胜感激。
最佳答案
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"] . "\n";
}
}
?>
关于php - 在 NetBeans 中使用 Slim Framework 将 Php 连接到 MongoDB,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24769669/