日期:2014-05-16  浏览次数:20448 次

mongoDB WindowsPHP连接安装测试(二)

安装好mongoDB数据库后,现在安装PHP连接mongoDB配置

二、在 PHP 里用代码进行测试:

与 MySQL 一样,mongoDB 是以PHP 扩展库.dll 的形式与 PHP 进行集成的。

到以下网址下载 Windows 下相应PHP 版本的 dll 文件:
http://cn.php.net/manual/en/mongo.installation.php#mongo.installation.windows

根据自己的 PHP 的版本、是否线程安全(可在 phpinfo 里查看)等来选择相应版本,如:
PHP 5.2 VC6 Thread-Safe Mongo extension:
http://downloads.mongodb.org/mongo-latest-php5.2vc6ts.zip

下载,加压,得到 php_mongo.dll 文件。拷贝到 PHP 安装目录下的 ext 目录下在 php.ini 文件里加:

extension = php_mongo.dll;

重启 Web 服务器(apache 或 nginx)。应该能在 phpinfo 里看到 mingoDB 的信息,否则就是安装有问题。很可能是下载的 mingoDB 扩展不对。

<?php
ini_set ( 'error_reporting', E_ALL | E_STRICT ); //打开错误显示开关
//ini_set('error_reporting', 0); //关闭错误输出

$dburl = 'localhost';
$port = '27017';
$dbname = 'testdb';
$username = '';
$password = '';

$connection = new Mongo (); // connects to localhost:27017
//$connection = new Mongo( "$dburl:$port" ); // connect to a remote host (default port)

$db = $connection->selectDB ( $dbname );

$collection = $db->selectCollection ( 'myc' );

$doc = array ("name" => "MongoDB", "type" => "database", "count" => 1, "info" => ( object ) array ("x" => 100, "y" => 200 ), "versions" => array ("0.9.7", "0.9.8", "1.4.0" ) );
//$ret = $collection->insert($doc);

//遍历:
$cursor = $collection->find ();
//var_dump($cursor); //object(MongoCursor)[5] 5个对象
//返回$collection集合中文档的数量
echo '文档条数:' . $collection->count ();
//
echo '<br>';
foreach ( $cursor as $val ) {
	echo $val ['_id'] . ': ' . $val ['name'] . '--' . $val ['type'] . '--' . $val ['info'] ['x'] . '--' . $val ['info'] ['y'] . '--' . $val ['versions'] [2] . '<br>';
}

//更新:
//
$collection->update ( array ("a" => 10 ), array ('$set' => array ('a' => 10000 ) ) );
//
$options ['multiple'] = true; //默认是 false,是否改变匹配的多行
$collection->update ( array ("info.x" => 100 ), array ('$set' => array ('info.y' => 800 ) ), $options );

//按条件查找:
$query = array ("a" => 10000 );
$cursor = $collection->find ( $query ); //在$collectio集合中查找满足$query的文档
while ( $cursor->hasNext () ) {
	var_dump ( $cursor->getNext () ); //返回了数组
}

//$collection -> findOne(); //返回$collection集合中第一个文档
//$joe = $collection->findOne(array("_id" => $ret['_id']));

//删除一个数据库:
//$connection->dropDB("...");
//$connection->dropDB("...");

//列出所有可用数据库:
$m->listDBs (); //无返回值

//关闭连接:
$connection->close ();
?>