您好,欢迎来到三六零分类信息网!老站,搜索引擎当天收录,欢迎发信息

PHP数据库基于PDO操作类(mysql)

2025/8/9 20:36:48发布24次查看
本篇文章分享的内容是php数据库基于pdo操作类(mysql),现在分享给大家,有需要的朋友可以参考一下本篇文章的内容
php数据库基于pdo操作类(mysql)
这是网上找的关于mysql的操作类,非常适合初学者使用
<?phpclass mysql { protected static $_dbh = null; //静态属性,所有数据库实例共用,避免重复连接数据库 protected $_dbtype = 'mysql'; protected $_pconnect = true; //是否使用长连接 protected $_host = 'localhost'; protected $_port = 3306; protected $_user = 'root'; protected $_pass = ''; protected $_dbname = null; //数据库名 protected $_sql = false; //最后一条sql语句 protected $_where = ''; protected $_order = ''; protected $_limit = ''; protected $_field = '*'; protected $_clear = 0; //状态,0表示查询条件干净,1表示查询条件污染 protected $_trans = 0; //事务指令数 /** * 初始化类 * @param array $conf 数据库配置 */ public function __construct(array $conf) { class_exists('pdo') or die("pdo: class not exists."); $this->_host = $conf['host'];            $this->_port = $conf['port'];            $this->_user = $conf['user'];            $this->_pass = $conf['password'];            $this->_dbname = $conf['dbname'];            //连接数据库             if ( is_null(self::$_dbh) ) {                $this->_connect();             }         }        /**          * 连接数据库的方法         */         protected function _connect() {            $dsn = $this->_dbtype.':host='.$this->_host.';port='.$this->_port.';dbname='.$this->_dbname;            //持久化连接             $options = $this->_pconnect ? array(pdo::attr_persistent=>true) : array();            try {                  $dbh = new pdo($dsn, $this->_user, $this->_pass, $options);                $dbh->setattribute(pdo::attr_errmode, pdo::errmode_exception);  //设置如果sql语句执行错误则抛出异常,事务会自动回滚                 $dbh->setattribute(pdo::attr_emulate_prepares, false); //禁用prepared statements的仿真效果(防sql注入)             } catch (pdoexception $e) {                  die('connection failed: ' . $e->getmessage());             }            $dbh->exec('set names utf8');             self::$_dbh = $dbh;         }        /**          * 字段和表名添加 `符号         * 保证指令中使用关键字不出错 针对mysql          * @param string $value          * @return string          */         protected function _addchar($value) {              if ('*'==$value || false!==strpos($value,'(') || false!==strpos($value,'.') || false!==strpos($value,'`')) {                  //如果包含* 或者 使用了sql方法 则不作处理              } elseif (false === strpos($value,'`') ) {                  $value = '`'.trim($value).'`';             }              return $value;          }        /**          * 取得数据表的字段信息          * @param string $tbname 表名         * @return array          */         protected function _tbfields($tbname) {            $sql = 'select column_name from information_schema.columns where table_name='.$tbname.' and table_schema='.$this->_dbname.'';            $stmt = self::$_dbh->prepare($sql);            $stmt->execute();            $result = $stmt->fetchall(pdo::fetch_assoc);            $ret = array();            foreach ($result as $key=>$value) {                $ret[$value['column_name']] = 1;             }            return $ret;         }        /**          * 过滤并格式化数据表字段         * @param string $tbname 数据表名          * @param array $data post提交数据          * @return array $newdata          */         protected function _dataformat($tbname,$data) {            if (!is_array($data)) return array();            $table_column = $this->_tbfields($tbname);            $ret=array();            foreach ($data as $key=>$val) {                if (!is_scalar($val)) continue; //值不是标量则跳过                 if (array_key_exists($key,$table_column)) {                    $key = $this->_addchar($key);                    if (is_int($val)) {                          $val = intval($val);                      } elseif (is_float($val)) {                          $val = floatval($val);                      } elseif (preg_match('/^\(\w*(\+|\-|\*|\/)?\w*\)$/i', $val)) {                        // 支持在字段的值里面直接使用其它字段 ,例如 (score+1) (name) 必须包含括号                         $val = $val;                     } elseif (is_string($val)) {                          //将字符串中的单引号(')、双引号()、反斜线(\)与 nul(null 字符转义                         $val = ''.addslashes($val).'';                     }                    $ret[$key] = $val;                 }             }            return $ret;         }        /**         * 执行查询 主要针对 select, show 等指令         * @param string $sql sql指令          * @return mixed          */         protected function _doquery($sql='') {            $this->_sql = $sql;            $pdostmt = self::$_dbh->prepare($this->_sql); //prepare或者query 返回一个pdostatement             $pdostmt->execute();            $result = $pdostmt->fetchall(pdo::fetch_assoc);            return $result;         }        /**          * 执行语句 针对 insert, update 以及delete,exec结果返回受影响的行数         * @param string $sql sql指令          * @return integer          */         protected function _doexec($sql='') {            $this->_sql = $sql;            return self::$_dbh->exec($this->_sql);         }        /**          * 执行sql语句,自动判断进行查询或者执行操作          * @param string $sql sql指令          * @return mixed          */         public function dosql($sql='') {            $queryips = 'insert|update|delete|replace|create|drop|load data|select .* into|copy|alter|grant|revoke|lock|unlock';              if (preg_match('/^\s*?(' . $queryips . ')\s+/i', $sql)) {                  return $this->_doexec($sql);             }            else {                //查询操作                 return $this->_doquery($sql);             }         }        /**          * 获取最近一次查询的sql语句          * @return string 执行的sql          */         public function getlastsql() {              return $this->_sql;         }        /**          * 插入方法          * @param string $tbname 操作的数据表名          * @param array $data 字段-值的一维数组          * @return int 受影响的行数         */         public function insert($tbname,array $data){            $data = $this->_dataformat($tbname,$data);            if (!$data) return;            $sql = insert into .$tbname.(.implode(',',array_keys($data)).) values(.implode(',',array_values($data)).);            return $this->_doexec($sql);         }        /**          * 删除方法          * @param string $tbname 操作的数据表名          * @return int 受影响的行数         */         public function delete($tbname) {            //安全考虑,阻止全表删除             if (!trim($this->_where)) return false;            $sql = delete from .$tbname. .$this->_where;            $this->_clear = 1;            $this->_clear();            return $this->_doexec($sql);         }        /**          * 更新函数          * @param string $tbname 操作的数据表名          * @param array $data 参数数组          * @return int 受影响的行数         */         public function update($tbname,array $data) {            //安全考虑,阻止全表更新             if (!trim($this->_where)) return false;            $data = $this->_dataformat($tbname,$data);            if (!$data) return;            $valarr = '';            foreach($data as $k=>$v){                $valarr[] = $k.'='.$v;             }            $valstr = implode(',', $valarr);            $sql = update .trim($tbname). set .trim($valstr). .trim($this->_where);            return $this->_doexec($sql);         }        /**          * 查询函数          * @param string $tbname 操作的数据表名          * @return array 结果集         */         public function select($tbname='') {            $sql = select .trim($this->_field). from .$tbname. .trim($this->_where). .trim($this->_order). .trim($this->_limit);            //echo $sql;             $this->_clear = 1;            $this->_clear();            return $this->_doquery(trim($sql));         }        /**          * @param mixed $option 组合条件的二维数组,例:$option['field1'] = array(1,'=>','or')          * @return $this         */         public function where($option) {            if ($this->_clear>0) $this->_clear();            $this->_where = ' where ';            $logic = 'and';            if (is_string($option)) {                $this->_where .= $option;             }            elseif (is_array($option)) {                foreach($option as $k=>$v) {                    if (is_array($v)) {                        $relative = isset($v[1]) ? $v[1] : '=';                        $logic    = isset($v[2]) ? $v[2] : 'and';                        $condition = ' ('.$this->_addchar($k).' '.$relative.' '.$v[0].') ';                     }                    else {                        $logic = 'and';                        $condition = ' ('.$this->_addchar($k).'='.$v.') ';                     }                    $this->_where .= isset($mark) ? $logic.$condition : $condition;                    $mark = 1;                 }             }            return $this;         }        /**          * 设置排序          * @param mixed $option 排序条件数组 例:array('sort'=>'desc')          * @return $this         */         public function order($option) {            if ($this->_clear>0) $this->_clear();            $this->_order = ' order by ';            if (is_string($option)) {                $this->_order .= $option;             }            elseif (is_array($option)) {                foreach($option as $k=>$v){                    $order = $this->_addchar($k).' '.$v;                    $this->_order .= isset($mark) ? ','.$order : $order;                    $mark = 1;                 }             }            return $this;         }        /**          * 设置查询行数及页数          * @param int $page pagesize不为空时为页数,否则为行数          * @param int $pagesize 为空则函数设定取出行数,不为空则设定取出行数及页数          * @return $this         */         public function limit($page,$pagesize=null) {            if ($this->_clear>0) $this->_clear();            if ($pagesize===null) {                $this->_limit = limit .$page;             }            else {                $pageval = intval( ($page - 1) * $pagesize);                $this->_limit = limit .$pageval.,.$pagesize;             }            return $this;         }        /**          * 设置查询字段          * @param mixed $field 字段数组          * @return $this         */         public function field($field){            if ($this->_clear>0) $this->_clear();            if (is_string($field)) {                $field = explode(',', $field);             }            $nfield = array_map(array($this,'_addchar'), $field);            $this->_field = implode(',', $nfield);            return $this;         }        /**          * 清理标记函数         */         protected function _clear() {            $this->_where = '';            $this->_order = '';            $this->_limit = '';            $this->_field = '*';            $this->_clear = 0;         }        /**          * 手动清理标记          * @return $this         */         public function clearkey() {            $this->_clear();            return $this;         }        /**         * 启动事务          * @return void          */         public function starttrans() {              //数据rollback 支持              if ($this->_trans==0) self::$_dbh->begintransaction();            $this->_trans++;              return;          }        /**          * 用于非自动提交状态下面的查询提交          * @return boolen          */         public function commit() {            $result = true;            if ($this->_trans>0) {                  $result = self::$_dbh->commit();                  $this->_trans = 0;             }              return $result;         }        /**          * 事务回滚          * @return boolen          */         public function rollback() {            $result = true;            if ($this->_trans>0) {                $result = self::$_dbh->rollback();                $this->_trans = 0;             }            return $result;         }        /**         * 关闭连接         * php 在脚本结束时会自动关闭连接。        */         public function close() {            if (!is_null(self::$_dbh)) self::$_dbh = null;         } }
相关推荐:
php数据库保存session会话
php数据库比较工具分享
php数据库操作记录
以上就是php数据库基于pdo操作类(mysql)的详细内容。
该用户其它信息

VIP推荐

免费发布信息,免费发布B2B信息网站平台 - 三六零分类信息网 沪ICP备09012988号-2
企业名录 Product