第六部分 PHP实例
第六部分 实战篇
想在PHP中调用Mongo需要安装MongoDB的PHP扩展
1) 首先下载最新的php mongodb扩展源码,源码可以在http://pecl.php.net/paclcage/mongo下载
2) 解压
wget http://pecl.php.net/paclcage/mongo
tar zxf mongo-1.2.6.tgz
ch mongo-1.2.6
3) 进入文件夹后,运行phpize来准备编译扩展的环境
/usr/local/php/bin/phpize
4) 运行后,我们运行./configure脚本来进行配置
./cinfigure --with-php-config=/usr/local/php/bin/php-config
--with-php-config这个参数是告诉配置脚本php-config这个程序的路径
5)这里用make来编译扩展
make && make install
正确编译数据结果
完成后,请编辑你的php.ini文件增加一行
extension=mongo.so
一般默认的编译php.ini文件/usr/local/php/etc/php.ini
重启Apache打开phpinfo
看到mongo 模块,主证明MongoDB的php扩展安装成功
这块安装配置在服务器上太慢了,网慢哦,等虚拟机弄起来在弄吧
给php打mongo模块
(1): 执行 /usr/local/php/bin/phpize
(2): ./configure --with-php-config=/usr/local/php/bin/php-cinfig --enable-mongo
(3): 在php.ini中添加上mongo.os加上去
(4): 重载apache
后面讲这种弄不懂样,多看看他们的视频吧
在php的mongo扩展中,提供了四类接口(对象):
1 针对mongoDB连接的操作:Mongo
2 针对mongoDB中数据库的操作: MongoDB
3 针对MongoDB中collection的操作: MongoCollection
4 针对查询结果集的操作:MongoCursor
1 连接Mongo服务器
$db->close();
连接数据库:
<?php
$conn = new Mongo("mongodb://user1:123456@localhost:27017/test");
$db = $conn->test;
?>
查询数据:
<?php
include "conn.php";
$c1 = $db->c1;
//db.c1.find({"age":{$gt:40}});
//{name:"user1"}==array("name"=>"user1");
//[1,2] = array(1,2);
$arr = array();
$ret = $c1->find($arr);
foreach ($ret as $val) {
//echo "id:{$val['_id']}<BR>";
///echo "name:{$val['name']}<BR>";
$age = isset($val['age']) ? $val['age'] : 0;
echo "<a href='user.php?id={$val['_id']}'>{$val['name']}</a> age:{$age}---<a href='delete.php?name={$val['name']}'>del</a>--<a href='update.php?id={$val['_id']}'>update</a>";
echo "<BR><BR><BR>";
}
?>
修改:
<?php
include "conn.php";
$c1 = $db->c1;
//$db.c1.update({name:"user1"},{$set:{age:300}});
$id = new MongoId($_GET['id']);
$arr=array('_id'=>$id);
$darr = array('$set'=>array('age'=>250));
$opts = array('upsert'=>false,'multiple'=>true);
//相当于db.update()后面的第三跟第四个叁数
if($c1->update($arr,$darr, $opts)){
echo "<script>location='find.php'</script>";
}else{
echo "更改失败!";
}
?>
插入:
<?php
include "conn.php";
$c1 = $db->c1;
//db.c1.insert({name:"user3", age:30, sex:"man"});
$arr = array("name"=>"user3", "age"=>30, "sex"=>"man");
if($c1->insert($arr)){
echo "<script>location='find.php'</script>";
}else{
echo "插入数据失败!";
}
?>
删除:
<?php
include "conn.php";
$c1 = $db->c1;
//db.c1.remover({"name":"user2"});
$name = $_GET['name'];
if(!empty($name))
{
$arr = array("name"=>$name);
if($c1->remove($arr)){
echo "<script>location='find.php'</script>";
}else{
echo "删除失败";
}
}else{
echo "数据为空!";
}
?>
详细信息:
<?php
include "conn.php";
$c1 = $db->c1;
//db.c1.find({_id:ObjectId("123456")};
$oid = new MongoId($_GET['id']);
$arr = array("_id"=>$oid);
$ret = $c1->findOne($arr);
var_dump($ret);
?>