-
Notifications
You must be signed in to change notification settings - Fork 131
数据库操作(Ezsql)
Yi Xian edited this page Dec 1, 2016
·
6 revisions
Ezsql目前已完全集成到Phprs中,是一个简单易用的数据库操作类,可操作的数据库包括但不限于Mysql、MsSql。
使用方法非常简单,直接修改下配置文件conf.php就可以,在配置文件的最后加上数据库配置相关内容,包括数据库名称、用户名、密码等。
//db config sample, and ezphp can work with PDO simply
,
"db"=>[
"singleton"=>true,
"class"=>"PDO",
"pass_by_construct"=>true,
"properties"=>[
"dsn"=>"mysql:host=127.0.0.1;dbname=xxxxxx;charset=UTF8",
"username"=>"xxxxxx",
"passwd"=>"xxxxxx"
]
]
具体可参看:/example/conf.php中的示例。
下面是一段调出数据库中所有记录的范例供参考。
<?php
use phprs\util\Verify;
use phprs\util\exceptions\Forbidden;
use phprs\util\Logger;
use phprs\util\exceptions\NotFound;
use phprs\ezsql\Sql;
use phprs\util\exceptions\BadRequest;
/**
* @path("/orders/")
*/
class Orders
{
/**
* 获得db_orders中所有的数据记录
* @route({"GET","/"})
* @return({"body"})
*/
public function getAllOrders() {
return Sql::select('*')->from('db_orders')->get($this->db);
}
/**
* 依据带参数的路由url中的id来获得指定数据
* @route({"GET","/*"})
* @param({"id", "$.path[1]"})
* @return({"body"})
*/
public function getOrderById($id) {
return Sql::select('*')->from('db_orders')->where('id=?',$id)->get($this->db);
}
/**
* 下面定义使用在conf.php中配置的默认数据库
* @property({"default":"@db"})
* @var \PDO
*/
public $db;
}
$res = Sql::select('a, b')
->from('table')
->leftJoin('table1')->on('table.id=table1.id')
->where('a=?',1)
->groupBy('b')->having('sum(b)=?', 2)
->orderBy('c', Sql::$ORDER_BY_ASC)
->limit(0,1)
->forUpdate()->of('d')
->get($db);
$rows = Sql::update('table')
->set('a', 1)
->where('b=?', 2)
->orderBy('c', Sql::$ORDER_BY_ASC)
->limit(1)
->exec($db)
->rows
$newId = Sql::insertInto('table')
->values(['a'=>1])
->exec($db)
->lastInsertId()
$rows = Sql::deleteFrom('table')
->where('b=?', 2)
->orderBy('c', Sql::$ORDER_BY_ASC)
->limit(1)
->exec($db)
->rows
带条件的查询示例
$result = Sql::select('*')->from('db_orders')->where('id=?',$id)->get($this->db);
带多个条件的查询示例(AND、OR)
$res = Sql::select('uid')->from('db_orders')->where('realname = ? AND uid <> ?', $realnameval, $uidval)->get($this->db);
Phprs分页实现 待更新...
更多参看示例文件:/example/apis/Users.php