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