单例模式实现简单的mysql操作类
单例模式实现简单的mysql操作类
为什么要弄个抽象类,原因是不清楚还会不会在代码基础上继续拓展。所以就先写上了。
代码:
抽象类:
<?php abstract class Mysql { abstract protected function connect(); abstract protected function query($sql); abstract protected function err($sql=''); }
操作类:
<?php require_once('./Mysql.php'); class db extends Mysql { private $config = array( 'DB_HOST' => '127.0.0.1', //主机 'DB_USER' => 'root', //用户名 'DB_PWD' => 'root', //密码 'DB_NAME' => 'test', //数据库名 'DB_CHARSET' => 'utf8', //字符集 ); private $link; //数据库连接标识; private $rows; //查询获取的多行数组 private $result; //查询结果 static $_instance; //存储对象 private function __construct($config=array()){ $this->config = $config ? $config : $this->config; $this->connect(); } //防止克隆 private function __clone(){} //连接数据库 public function connect() { $this->link = mysqli_connect($this->config['DB_HOST'],$this->config['DB_USER'],$this->config['DB_PWD']) or die(mysqli_connect_errno()); mysqli_select_db($this->link,$this->config['DB_NAME']) or die(mysqli_error($this->link)); $this->query("SET NAMES ".$this->config['DB_CHARSET']); return $this->link; } //查询数据 public function query($sql) { $this->result = mysqli_query($this->link,$sql) or $this->err($sql); return $this->result; } protected function err($sql='') { echo '错误得sql语句'.$sql; exit; } //单例模式 public static function getInstance(){ if(FALSE == (self::$_instance instanceof self)){ self::$_instance = new self(); } return self::$_instance; } //查询单挑记录 public function getRow($sql, $type = MYSQLI_ASSOC) { $result = $this->query($sql); return mysqli_fetch_array($result, $type); } /** * 多行记录 */ public function getRows($sql, $type = MYSQLI_ASSOC) { $result = $this->query($sql); while ($row = mysqli_fetch_array($result, $type)) { $this->rows[] = $row; } return $this->rows; } //插入数据 public function insert($table,$data) { $str = ''; $str .= "INSERT INTO `$table`"; $str .= "(`".implode("`,`",array_keys($data))."`)"; $str .= " VALUES "; $str .= "('".implode("','",$data)."')"; $result = $this->query($str); if ($result && mysqli_affected_rows($this->link)>0) { return mysqli_insert_id($this->link); }else{ return false; } } //插入数据 public function update($table,$data,$where) { if (!$where) { die('条件不能为空'); } $str = ''; $str .= "UPDATE `$table` SET "; foreach ($data as $key => $value) { $str .='`'.$key.'`="'.$value.'",'; } $str = rtrim($str,','); $str .= ' where '.$where; $result = $this->query($str); if ($result && mysqli_affected_rows($this->link)>0) { return mysqli_affected_rows($this->link); }else{ return false; } } //删除数据 public function delete($table,$where) { if (!$where) { die('条件不能为空'); } $str = "DELETE FROM `$table` WHERE $where "; $result = $this->query($str); if ($result && mysqli_affected_rows($this->link)>0) { return mysqli_affected_rows($this->link); }else{ return false; } } }