首页 > 代码库 > 基于mysqli的数据库操作类
基于mysqli的数据库操作类
<?php/*****************************数据库访问类(MySQLi版)******************************/class MySQLiDb{ //数据库链接本身 private $link; //最后一次执行的sql语句 private $sql; //初始化类 public function __construct($hostname,$username,$password,$database){ $this->link=new mysqli($hostname,$username,$password,$database); if(mysqli_connect_error()){ $errorInfo=‘Error:Could not make a database link (‘. mysqli_connect_errno().‘)‘.mysqli_connect_error(); throw new ErrorException($errorInfo, 1); } $this->link->set_charset("utf8"); } //获取插入后生成的ID private function getLastId(){ return $this->link->insert_id; } //获取影响的行数 private function countAffected(){ return $this->link->affected_rows; } //将数组格式的条件组装成字符串 private function rewhere($where){ $str=‘‘; foreach($where as $key=>$value){ if(!empty($str)){ $str.=‘ and ‘; } $rekey=$this->link->escape_string($key); $revalue=$this->link->escape_string($value); $str.=is_numeric($revalue)?"`$rekey`=$revalue":"`$rekey`=‘$revalue‘"; } return $str; } public function create($table,$model){ $fields=‘‘; $values=‘‘; foreach ($model as $key => $value) { if($fields){ $fields.=‘,‘; } $fields.="`$key`"; if($values){ $values.=‘,‘; } $values.=is_numeric($value)?$value:"‘".$this->link->escape_string($value)."‘"; } $this->sql="INSERT INTO `$table`($fields) VALUES($values)"; echo $this->sql; $this->link->query($this->sql); return $this->link->insert_id; } public function modify($table,$model,$where){ $assins=‘‘; $where=$this->rewhere($where); foreach ($model as $key => $value) { $rkey=$this->link->escape_string($key); $rvalue=$this->link->escape_string($value); if(!is_numeric($rvalue)){ $rvalue="‘".$rvalue."‘"; } $assins.=$assins?",`$rkey`=$rvalue":"`$rkey`=$rvalue"; } $this->sql="UPDATE `$table` SET $assins WHERE $where"; echo $this->sql; $this->link->query($this->sql); } public function remove($table,$where){ $where=$this->rewhere($where); $this->sql="DELETE FROM `$table` WHERE $where"; echo $this->sql; $this->link->query($this->sql); } public function search($table,$where){ $where=$this->rewhere($where); $this->sql="SELECT * FROM `$table` WHERE $where"; $this->link->query($this->sql); $result=$this->link->query($this->sql); return $result -> fetch_assoc(); } public function unique($table,$where){ $where=$this->rewhere($where); $this->sql="SELECT * FROM `$table` WHERE $where LIMIT 1"; $result=$this->link->query($this->sql); return $result -> fetch_object(); }}
基于mysqli的数据库操作类
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。