您好,登录后才能下订单哦!
密码登录
登录注册
点击 登录注册 即表示同意《亿速云用户服务条款》
这篇文章将为大家详细讲解有关PHP基于单例模式如何实现数据库操作基类,小编觉得挺实用的,因此分享给大家做个参考,希望大家阅读完这篇文章后可以有所收获。
具体如下:
配置文件:
<?php $db = array( 'host'=>'localhost', 'user'=>'root', 'password'=>'', 'database'=>'test', ) ?>
php 数据库基类:
<?php class db { public $conn; public static $sql; public static $instance=null; private function __construct(){ require_once('db.config.php'); $this->conn = mysql_connect($db['host'],$db['user'],$db['password']); if(!mysql_select_db($db['database'],$this->conn)){ echo "失败"; }; mysql_query('set names utf8',$this->conn); } public static function getInstance(){ if(is_null(self::$instance)){ self::$instance = new db; } return self::$instance; } /** * 查询数据库 */ public function select($table,$condition=array(),$field = array()){ $where=''; if(!empty($condition)){ foreach($condition as $k=>$v){ $where.=$k."='".$v."' and "; } $where='where '.$where .'1=1'; } $fieldstr = ''; if(!empty($field)){ foreach($field as $k=>$v){ $fieldstr.= $v.','; } $fieldstr = rtrim($fieldstr,','); }else{ $fieldstr = '*'; } self::$sql = "select {$fieldstr} from {$table} {$where}"; $result=mysql_query(self::$sql,$this->conn); $resuleRow = array(); $i = 0; while($row=mysql_fetch_assoc($result)){ foreach($row as $k=>$v){ $resuleRow[$i][$k] = $v; } $i++; } return $resuleRow; } /** * 添加一条记录 */ public function insert($table,$data){ $values = ''; $datas = ''; foreach($data as $k=>$v){ $values.=$k.','; $datas.="'$v'".','; } $values = rtrim($values,','); $datas = rtrim($datas,','); self::$sql = "INSERT INTO {$table} ({$values}) VALUES ({$datas})"; if(mysql_query(self::$sql)){ return mysql_insert_id(); }else{ return false; }; } /** * 修改一条记录 */ public function update($table,$data,$condition=array()){ $where=''; if(!empty($condition)){ foreach($condition as $k=>$v){ $where.=$k."='".$v."' and "; } $where='where '.$where .'1=1'; } $updatastr = ''; if(!empty($data)){ foreach($data as $k=>$v){ $updatastr.= $k."='".$v."',"; } $updatastr = 'set '.rtrim($updatastr,','); } self::$sql = "update {$table} {$updatastr} {$where}"; return mysql_query(self::$sql); } /** * 删除记录 */ public function delete($table,$condition){ $where=''; if(!empty($condition)){ foreach($condition as $k=>$v){ $where.=$k."='".$v."' and "; } $where='where '.$where .'1=1'; } self::$sql = "delete from {$table} {$where}"; return mysql_query(self::$sql); } public static function getLastSql(){ echo self::$sql; } } $db = db::getInstance(); //$list = $db->select('demo',array('name'=>'tom','password'=>'ds'),array('name','password')); //echo $db->insert('demo',array('name'=>'亿速云','password'=>'123')); //echo $db->update('demo',array("name"=>'xxx',"password"=>'123'),array('id'=>1)); echo $db->delete('demo',array('id'=>'2')); db::getLastSql(); echo "<pre>"; ?>
关于“PHP基于单例模式如何实现数据库操作基类”这篇文章就分享到这里了,希望以上内容可以对大家有一定的帮助,使各位可以学到更多知识,如果觉得文章不错,请把它分享出去让更多的人看到。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。