PHP操作mongodb:
PHP 要操作mongodb需要打模块
官网可以下载:http://pecl.php.net/package/mongo 下载
mongodb设置成用户授权的启动方式
php手册没有些用户授权方式登陆的方法:
conn.php
<?php
$conn = new Mongo("mongodb://user1:[email protected]:27017/test"); //用户授权链接mongodb test数据库
$db = $conn->test;
?>
find.php
<?php
include "conn.php";
$c1 = $db->c1; //操作c1集合
//由于php里面不能直接用json
//db.c1.find({name:"user1"}); 不能这么玩
//{name:"user1"} == array("name"=>"user1") 用这种形式
//[1,2] == array(1,2);
//{} == array()
$arr=array();
$rst = $c1->find($arr);
foreach($rst as $val){
echo "<pre>";
print_r($val[‘name‘]); //取id的话 得"_id"
}
例子2:指定值查询
$arr = array("name"=>"user1"); //查询nam=user1的
$rst = $c1->find($arr);
foreach($rst as $val){
echo "<pre>";
$fis = $val[‘_id‘];
print_r($val);
echo "<a href=‘user.php?fid={$fid}‘></a>"; //你会发现fid传到user.php的时候变成字符串了,怎么解决?
//user.php 根据_id查mongodb对应的数据
<?php
include "conn.php";
$c1 = $db->c1;
$oid= new MongoId($_GET[‘fid‘]); 用这个转一下
var_dump($oid); //还是Object,不转的话就是string类型
$arr = array("_id"=>"$oid");
$rst = $c1->find($arr);
foreach($rst as $val){
echo "<pre>";
print_r($val);
}
?>
}
例子3:增加
include "conn.php";
$c1 = $db->c1;
//db.c1.insert({"name"=>"user3",age:30,"sex"=>"nan"});
$arr = array("name"=>"user3","age"=>30,"sex"=>"nan");
if($c1->insert($arr))
echo ‘成功‘;
else
echo ‘失败‘;
例子4:删
include "conn.php";
$c1 = $db->c1;
//db.c1.remove({"name"=>"user2"});
$arr = array("name"=>"user2");
if($c1->remove($arr))
echo ‘删除成功‘;
else
echo ‘删除失败‘;
例子4:改
include "conn.php";
$c1 = $db->c1;
//db.c1.update({"name"=>"user2"},{$set:{age:20,sex:"nan"}}); 增加字段
$sarr = array("name"=>"user2");
$darr = array(‘$set‘=>array(‘sex‘=>‘nan‘,‘age‘=>24));
$opts = array(‘upsert‘=>0,‘multiple‘=>1);
if($c1->update($sarr,$darr,$opts)) //php里面的update只能传3个参数
echo ‘更改成功‘;
else
echo ‘更改失败‘;
//关闭
$conn->close();
?>