0

直接访问 PHP 文件时,我没有从数据库返回任何结果,但是echo下面的所有检查都返回了预期的结果。

这是整个 PHP 文件。

<?php 

$ext = new ReflectionExtension('mongo');  // see http://php.net/manual/en/reflectionextension.getversion.php
var_dump($ext->getVersion());  // returns string(5) "1.3.4"

echo extension_loaded("mongo") ? "loaded<br />" : "not loaded<br />";  // check if driver installed - returns "loaded"

$dbhost = '127.x.xx.x';
$dbname = 'mydb';
$m = new Mongo("mongodb://$dbhost");  // also tried 'MongoClient' rather than 'Mongo'
if ($m == true) {
echo "<br />connected to {$m}<br />";  // returns "connected to 127.x.xx.x:27017
}
$db = $m->$dbname;
$collection = $db->myCollection;
echo "<br />my collection is called {$collection}<br />";  // returns "my collection is called mydb.myCollection"
$query = $collection->find();
if ($query == true) {
echo "<br />the find method works";  // this is being returned
}
foreach($query as $result) { // nothing is happening here
var_dump($result);
}

?>

命令行查询:

db.myCollection.find();

正在返回预期结果(有一个文档)。

4

2 回答 2

0

您使用的是什么版本的 PECL mongo lib?如果 >= 1.3.0(我们现在是 1.4.3 稳定版),则不Mongo推荐使用该类,鼓励您改用该类MongoClient。请参考phpDoc

于 2013-09-03T12:52:19.013 回答
0

解决方案

将上面的代码调整为:

$dbhost = 'username:password@127.x.xx.x:27017/';
$dbname = 'yourdbname';
$m = new MongoClient("mongodb://$dbhost"); 

就我而言,我需要定义 IP 地址。

于 2013-09-03T15:19:33.267 回答