<?php//三私一公 單例class Db{ //數據庫鏈接對象 private static $instance; private static $table_name; private $pdo; //防止類直接實例化 private function __construct(){ $this->pdo = new PDO("mysql:host=127.0.0.1;dbname=test_system", "root", ""); $this->pdo->query("set names utf8"); } //禁止克隆對象 private function __clone(){} //返回數據庫實例對象 public static function getDb($table_name){ self::$table_name = $table_name; if(!(self::$instance instanceof self)){ self::$instance = new self; } return self::$instance; } function add($table_name, $data){ $keys = implode(",", array_keys($data)); $value = "'".implode("','", array_values($data))."'"; $sql = "insert into $table_name ($keys) values($value) "; $r = $this->pdo->exec($sql); $this->getErrorInfo(); return $r; } function addAll($table_name, $data){ $keys = implode(",", array_keys($data[0])); $arr = []; foreach ($data as $k => $v) { $arr[] = "('".implode("','", array_values($v))."')"; } $value = implode(",", $arr); $sql = "insert into $table_name ($keys) values $value"; $r = $this->pdo->exec($sql); $this->getErrorInfo(); return $r; } function update($table_name, $data){ $id = $data['id']; unset($data['id']); $arr = []; foreach($data as $k=>$v){ $arr[] = $k."='".$v ."'"; } $str = implode(",", $arr); $sql = "update $table_name set $str where id=$id"; $r = $this->pdo->exec($sql); $this->getErrorInfo(); return $r; } function select($table_name, $where = '1=1'){ $sql = "select * from $table_name where $where "; $res = $this->pdo->query($sql)->fetchAll(PDO::FETCH_ASSOC); $this->getErrorInfo(); return $res; } function find($table_name, $where = '1=1'){ $sql = "select * from $table_name where $where "; $res = $this->pdo->query($sql)->fetch(PDO::FETCH_ASSOC); $this->getErrorInfo(); return $res; } function getErrorInfo(){ if($this->pdo->errorCode() != '00000'){ echo "<pre>"; print_r($this->pdo->errorInfo()); exit; } } function delete($id){ $table_name = self::$table_name; if(is_array($id)){ $id = implode(',', $id); } $sql = "delete from $table_name where id in ($id)"; $r = $this->pdo->exec($sql); $this->getErrorInfo(); return $r; }}function M($table_name){ $db = Db::getDb($table_name); return $db;};$data = [ [ 'name'=>'雪碧', 'class_name'=>'3333333', ], [ 'name'=>'可樂', 'class_name'=>'3333333', ],];$r = M('user')->delete(726);echo $r;