数据库查询构造器
class Query()
{
protected $db;//PDO连接对象
protected $table;
protected $field;
protected $where;
protected $Limit;
protected $select;
protected $toArray;
//连接数据库
private function connect($dsn,$username,$password)
{
$this->db=new PDO($dsn,$username,$password);
}
function __construct($dsn,$username,$password)
{
$this->connect($dsn,$username,$password);
}
//数据表方法$table
public function table($table)
{
$this->table=$table;
return $this;
}
//文件名方法$field
public function field($field)
{
$this->field=$field;
return $this;
}
//Limit方法$Limit
public function Limit($Limit)
{
$this->Limit=$Limit;
return $this;
}
//$where方法
public function where($where)
{
$this->where=$where;
return $this;
}
//$select方法
public function select($select)
{
$this->select=$select;
return $this;
}
public function getSql()
{
return printf('SELECT %s FROM $s LIMIT %d',$this->table,$this->field,$this->limit);
}
//执行查询
public function select()
{
return $this->db->query($this->getSql())->fetchAll(PDO::FETCH_ASSOC);
}
}
//工作类
class Db
{
static function __callStatic($method,$args){
$dsn='mysql:host=localhost;dbname=news';
$username='root';
$password='123456tyi';
$query=new Query( $dsn, $username, $password);
//直接委托给query中的具体方法来完成
return call_user_func([$query,$method],...args);
}
}
$res=Db::table('userid')->field('uid,uname')->Limit(1)->select();
echo '<pre>';
print_r($res);