PHP 要操作mongodb须要打模块
官网能够下载:http://pecl.php.net/package/mongo 下载
mongodb设置成用户授权的启动方式
php手冊没有些用户授权方式登陆的方法:
conn.php
<?
php
$conn = new Mongo("mongodb://user1:123456@localhost: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();
?
>