使用静态方法的重载技术, 实现一个数据库访问类
demo1.php文件
实例
require 'Query.php';
class Db
{
//数据库连接对象
protected static $pdo=null;
//数据库连接方法,每次查询时连接,实现真正的惰性连接,节省系统开销
public static function connection()
{
self::$pdo=new PDO('mysql:host=127.0.0.1;dbname=php','root','root');
// self::$pdo = new PDO('mysql:host=localhost;dbname=php','root','root');
}
//静态方法的重载
public static function __callStatic($name, $arguments)
{
//连接上数据库
self::connection();
//实例化查询类
$query=new Query(self::$pdo);
//访问Query中的方法
return call_user_func_array([$query,$name],[$arguments[0]]);
}
}
$cats=Db::table('category')
->field('cate_id,name,alias')
->where('cate_id>=1')
->select();
// 遍历查询结果
foreach ($cats as $cat){
print_r($cat);echo'
';
}
运行实例 »
点击 "运行实例" 按钮查看在线实例
Query.php文件
实例
class Query
{
//连接对象
public $pdo=null;
//数据库名称
public $table='';
//字段列表
public $field='';
//查询条件
public $where='';
//显示数量
public $limit=0;
//构造方法
public function __construct($pdo)
{
$this->pdo=$pdo;
}
//调用表名
public function table($tableName)
{
$this->table=$tableName;
//关键是这一步
return $this;
}
//字段
public function field($fields)
{
$this->field=$fields;
//关键是这一步
return $this;
}
//设置查询条件
public function where($where)
{
$this->where=$where;
return $this;
}
//设置显示数量
public function limit($limit)
{
$this->limit=$limit;
return $this;
}
//创建SQL语句
public function select()
{
//设置查询条件
$fields = empty($this->field) ? '*' : $this->field;
$where = empty($this->where) ? '' : ' WHERE '.$this->where;
$limit = empty($this->limit) ? '' : ' LIMIT '.$this->limit;
//SQL
$sql = 'SELECT '.$fields.' FROM '.$this->table. $where . $limit;
// 预处理查询
$stmt = $this->pdo->prepare($sql);
$stmt->execute();
return $stmt->fetchAll(PDO::FETCH_ASSOC);
}
}
运行实例 »
点击 "运行实例" 按钮查看在线实例