1 <?php 2 include ('ft.php'); 3 4 $db=Danli::show(); 5 //查詢 6 //$re=$db->table('stree')->where(['name'=>'四六級分數']); 7 // 8 //$data=$db->get(); 9 10 //添加 11 12 //$arr=$db->table('stree')->insert(['name'=>'四六級分數','email'=>'124fsdag']); 13 14 15 //var_dump($arr); 16 //刪除; 17 //$del=$db->del(['id'=>[2,3]]); 18 19 //修改 20 21 $db->table('stree')->where(['id'=>2]); 22 $res=$db->update(['name'=>'第一次改','email'=>'改第三方']); 23 var_dump($res); 24 25 26 27 //封裝語句 28 29 <?php 30 class Danli{ 31 //將複製後的數據存進屬性中,方便其餘方法調用 32 private $table=null; 33 private $where=null; 34 private $pdo; 35 36 37 38 private static $internet; 39 40 private function __construct() 41 { 42 //連接數據庫,私有的是爲了防止外部直接實例化 43 $this->pdo=new PDO("mysql:host=127.0.0.1;dbname=1611b","root","root"); 44 } 45 private function __clone() 46 { 47 //定義成私有的,防止外部clone內部方法 48 // TODO: Implement __clone() method. 49 } 50 public static function show(){ 51 //判斷類是否被實例化,若是沒有則實例化,並存進self::$internet中,self::$internet是調用靜態屬性 52 if(!(self::$internet instanceof Danli)){ 53 self::$internet=new Danli(); 54 } 55 return self::$internet; 56 } 57 function table($table){ 58 //定義表名,利用實例化的類->table可調用 59 $this->table=$table.' '; 60 return $this; 61 } 62 function where($where){ 63 //where後跟的條件,判斷輸是數組仍是字符串 64 if(is_array($where)){ 65 $str='where '; 66 foreach ($where as $k=>$v){ 67 68 $str.=$k.'='."'$v'".' and '; 69 70 } 71 $str=rtrim($str,' and '); 72 73 }else{ 74 $str=$where; 75 } 76 77 return $this->where=$str; 78 79 } 80 81 function get(){ 82 //查詢的封裝 83 return $this->pdo->query("select*from $this->table $this->where")->fetchAll(PDO::FETCH_ASSOC); 84 85 } 86 function insert($arr){ 87 //添加 88 $key=array_keys($arr); 89 $keys=implode(',',$key); 90 $str=''; 91 foreach ($arr as $k=>$v){ 92 $str.=','."'".$v."'"; 93 } 94 $str=substr($str,1); 95 return $this->pdo->exec("insert into $this->table ($keys)values($str)"); 96 } 97 function del($id){ 98 //刪除 99 $str=''; 100 $str1=''; 101 foreach ($id as $k=>$v){ 102 $str.=$k; 103 foreach ($v as $kk=>$vv){ 104 $str1.=','.$vv; 105 } 106 } 107 108 $str2=substr($str1,1); 109 110 $ids='where '.$str.' in '.'('.$str2.')'; 111 return $this->pdo->exec("delete from $this->table $ids"); 112 } 113 114 function update($res){ 115 //修改 116 $str=''; 117 foreach ($res as $k=>$v){ 118 $str.=','.$k.'='."'".$v."'"; 119 } 120 $str=substr($str,1); 121 return $this->pdo->exec("update $this->table set $str $this->where"); 122 } 123 124 } 125 126