批改状态:合格
老师批语:
<?php
class Query{
private static $db;
private $table;
private $limit;
private $field;
private $where;
private $order;
private function __construct()
{
}
public static function con($host='localhost',$user='root',$pwd='root',$db='heima'){
$dsn = 'mysql:host=' . $host . ';dbname=' . $db;
try {
$dbh = new PDO($dsn, $user, $pwd, array(PDO::ATTR_ERRMODE => PDO::ERRMODE_WARNING));
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
exit;
}
static::$db = $dbh;
return new static();
}
public function table(string $table){
$table?$this->table = $table:die('数据表不能为空');
return $this;
}
public function limit($limit){
$limit?$this->limit = $limit:5;
return $this;
}
public function field($field){
$this->field = str_replace("'","",$field);
return $this;
}
public function order($order){
if($order){
if(is_string($order)){
$order = str_replace("'","",$order);
$arr = explode(',',$order);
if(count($arr) > 1){
$order = "'".$arr[0]."' ".$arr[1];
}else{
$order = "'".$arr[0]."' asc";
}
}
$this->order = $order;
}
return $this;
}
public function where($where){
if(is_array($where)){
$condition='';
foreach ($where as $key => $val) {
if (is_numeric($val)) {
$condition = $key.'='.$val;
}else{
if(is_array($val)){
list($a,$b) = $val;
if($a == 'like'){
$condition.=$key .' like ' .'\'%'.$b.'%\' and ';
}else{
$condition.= $key." ".$a." ".$b.' and ';
}
}else{
$condition = $key.'=\"'.$val.'\"';
}
}
}
}else{
$condition = $where;
}
$condition=rtrim($condition,' and');
$this->where = $condition;
return $this;
}
public function getSql(){
$str ="select $this->field from $this->table ";
if($this->where) $str.="where ".$this->where;
if($this->order) $str.=" order by ".$this->order;
$str.=" limit ".(($this->limit==null)?5:$this->limit);
return $str;
}
public function select(){
return static::$db->query($this->getSql())->fetchAll(PDO::FETCH_ASSOC);
}
}
class Db{
static function __callStatic($method, $args)
{
$query = Query::con();
return call_user_func([$query,$method],...$args);
}
}
$res = Db::table('sp_goods')->field('goods_name,goods_id')->where(['goods_id'=>['>',12]])->order('goods_id','desc')->select();
echo "<pre>";
print_r($res);
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号