PHP以mysqli方式连接类完整代码实例

   2015-09-17 0
核心提示:这篇文章主要介绍了PHP以mysqli方式连接类完整代码实例,对于学习和了解mysqli都有很大的帮助,需要的朋友可以参考下

本文所述的是一个在PHP中以mysqli方式连接数据库的一个数据库类实例,该数据库类是从一个PHP的CMS中整理出来的,可实现PHP连接数据库类,MySQLi版,兼容PHP4,对于有针对性需要的朋友可根据此代码进行优化和修改。

<php
#==================================================================================================
# Filename: /db/db_mysqli.php
# Note : 连接数据库类,MySQLi版
#==================================================================================================
#[类库sql]
class db_mysqli
{
 var $query_count = 0;
 var $host;
 var $user;
 var $pass;
 var $data;
 var $conn;
 var $result;
 var $prefix = "qinggan_";
 //返回结果集类型,默认是数字+字符
 var $rs_type = MYSQLI_ASSOC;
 var $query_times = 0;#[查询时间]
 var $conn_times = 0;#[连接数据库时间]
 var $unbuffered = false;
 //定义查询列表
 var $querylist;
 var $debug = false;
 #[构造函数]
 function __construct($config=array())
 {
 $this->host = $config['host']  $config['host'] : 'localhost';
 $this->port = $config['port']  $config['port'] : '3306';
 $this->user = $config['user']  $config['user'] : 'root';
 $this->pass = $config['pass']  $config['pass'] : '';
 $this->data = $config['data']  $config['data'] : '';
 $this->debug = $config["debug"]  $config["debug"] : false;
 $this->prefix = $config['prefix']  $config['prefix'] : 'qinggan_';
 if($this->data)
 {
  $ifconnect = $this->connect($this->data);
  if(!$ifconnect)
  {
  $this->conn = false;
  return false;
  }
 }
 return true;
 }
 #[兼容PHP4]
 function db_mysqli($config=array())
 {
 return $this->__construct($config);
 }
 #[连接数据库]
 function connect($database="")
 {
 $start_time = $this->time_used();
 if(!$this->port) $this->port = "3306";
 $this->conn = @mysqli_connect($this->host,$this->user,$this->pass,"",$this->port) or false;
 if(!$this->conn)
 {
  return false;
 }
 $version = $this->get_version();
 if($version>"4.1")
 {
  mysqli_query($this->conn,"SET NAMES 'utf8'");
  if($version>"5.0.1")
  {
  mysqli_query($this->conn,"SET sql_mode=''");
  }
 }
 $end_time = $this->time_used();
 $this->conn_times += round($end_time - $start_time,5);#[连接数据库的时间]
 $ifok = $this->select_db($database);
 return $ifok  true : false;
 }
 function select_db($data="")
 {
 $database = $data  $data : $this->data;
 if(!$database)
 {
  return false;
 }
 $this->data = $database;
 $start_time = $this->time_used();
 $ifok = mysqli_select_db($this->conn,$database);
 if(!$ifok)
 {
  return false;
 }
 $end_time = $this->time_used();
 $this->conn_times += round($end_time - $start_time,5);#[连接数据库的时间]
 return true;
 }
 #[关闭数据库连接,当您使用持续连接时该功能失效]
 function close()
 {
 if(is_resource($this->conn))
 {
  return mysqli_close($this->conn);
 }
 else
 {
  return true;
 }
 }
 function __destruct()
 {
 return $this->close();
 }
 function set($name,$value)
 {
 if($name == "rs_type")
 {
  $value = strtolower($value) == "num"  MYSQLI_NUM : MYSQLI_ASSOC;
 }
 $this->$name = $value;
 }
 function query($sql)
 {
 if(!is_resource($this->conn))
 {
  $this->connect();
 }
 else
 {
  if(!mysql_ping($this->conn))
  {
   $this->close();
   $this->connect();
  }
 }
 if($this->debug)
 {
  $sqlkey = md5($sql);
  if($this->querylist)
  {
  $qlist = array_keys($this->querylist);
  if(in_array($sqlkey,$qlist))
  {
   $count = $this->querylist[$sqlkey]["count"] + 1;
   $this->querylist[$sqlkey] = array("sql"=>$sql,"count"=>$count);
  }else{
   $this->querylist[$sqlkey] = array("sql"=>$sql,"count"=>1);
  }
  }
  else{
  $this->querylist[$sqlkey] = array("sql"=>$sql,"count"=>1);
  }
 }
 $start_time = $this->time_used();
 $func = $this->unbuffered && function_exists("mysqli_multi_query")  "mysqli_multi_query" : "mysqli_query";
 $this->result = @$func($this->conn,$sql);
 $this->query_count++;
 $end_time = $this->time_used();
 $this->query_times += round($end_time - $start_time,5);#[查询时间]
 if(!$this->result)
 {
  return false;
 }
 return $this->result;
 }
 function get_all($sql="",$primary="")
 {
 $result = $sql  $this->query($sql) : $this->result;
 if(!$result)
 {
  return false;
 }
 $start_time = $this->time_used();
 $rs = array();
 $is_rs = false;
 while($rows = mysqli_fetch_array($result,$this->rs_type))
 {
  if($primary && $rows[$primary])
  {
  $rs[$rows[$primary]] = $rows;
  }
  else
  {
  $rs[] = $rows;
  }
  $is_rs = true;
 }
 $end_time = $this->time_used();
 $this->query_times += round($end_time - $start_time,5);#[查询时间]
 return ($is_rs  $rs : false);
 }
 function get_one($sql="")
 {
 $start_time = $this->time_used();
 $result = $sql  $this->query($sql) : $this->result;
 if(!$result)
 {
  return false;
 }
 $rows = mysqli_fetch_array($result,$this->rs_type);
 $end_time = $this->time_used();
 $this->query_times += round($end_time - $start_time,5);#[查询时间]
 return $rows;
 }
 function insert_id($sql="")
 {
 if($sql)
 {
  $rs = $this->get_one($sql);
  return $rs;
 }
 else
 {
  return mysqli_insert_id($this->conn);
 }
 }
 function insert($sql)
 {
 $this->result = $this->query($sql);
 $id = $this->insert_id();
 return $id;
 }
 function all_array($table,$condition="",$orderby="")
 {
 if(!$table)
 {
  return false;
 }
 $table = $this->prefix.$table;
 $sql = "SELECT * FROM ".$table;
 if($condition && is_array($condition) && count($condition)>0)
 {
  $sql_fields = array();
  foreach($condition AS $key=>$value)
  {
  $sql_fields[] = "`".$key."`='".$value."' ";
  }
  $sql .= " WHERE ".implode(" AND ",$sql_fields);
 }
 if($orderby)
 {
  $sql .= " ORDER BY ".$orderby;
 }
 $rslist = $this->get_all($sql);
 return $rslist;
 }
 function one_array($table,$condition="")
 {
 if(!$table)
 {
  return false;
 }
 $table = $this->prefix.$table;
 $sql = "SELECT * FROM ".$table;
 if($condition && is_array($condition) && count($condition)>0)
 {
  $sql_fields = array();
  foreach($condition AS $key=>$value)
  {
  $sql_fields[] = "`".$key."`='".$value."' ";
  }
  $sql .= " WHERE ".implode(" AND ",$sql_fields);
 }
 $rslist = $this->get_one($sql);
 return $rslist;
 }
 //将数组写入数据中
 function insert_array($data,$table,$insert_type="insert")
 {
 if(!$table || !is_array($data) || !$data)
 {
  return false;
 }
 $table = $this->prefix.$table;//自动增加表前缀
 if($insert_type == "insert")
 {
  $sql = "INSERT INTO ".$table;
 }
 else
 {
  $sql = "REPLACE INTO ".$table;
 }
 $sql_fields = array();
 $sql_val = array();
 foreach($data AS $key=>$value)
 {
  $sql_fields[] = "`".$key."`";
  $sql_val[] = "'".$value."'";
 }
 $sql.= "(".(implode(",",$sql_fields)).") VALUES(".(implode(",",$sql_val)).")";
 return $this->insert($sql);
 }
 //更新数据
 function update_array($data,$table,$condition)
 {
 if(!$data || !$table || !$condition || !is_array($data) || !is_array($condition))
 {
  return false;
 }
 $table = $this->prefix.$table;//自动增加表前缀
 $sql = "UPDATE ".$table." SET ";
 $sql_fields = array();
 foreach($data AS $key=>$value)
 {
  $sql_fields[] = "`".$key."`='".$value."'";
 }
 $sql.= implode(",",$sql_fields);
 $sql_fields = array();
 foreach($condition AS $key=>$value)
 {
  $sql_fields[] = "`".$key."`='".$value."' ";
 }
 $sql .= " WHERE ".implode(" AND ",$sql_fields);
 return $this->query($sql);
 }
 function count($sql="")
 {
 if($sql)
 {
  $this->rs_type = MYSQLI_NUM;
  $this->query($sql);
  $rs = $this->get_one();
  $this->rs_type = MYSQLI_ASSOC;
  return $rs[0];
 }
 else
 {
  return mysqli_num_rows($this->result);
 }
 }
 function num_fields($sql="")
 {
 if($sql)
 {
  $this->query($sql);
 }
 return mysqli_num_fields($this->result);
 }
 function list_fields($table)
 {
 $rs = $this->get_all("SHOW COLUMNS FROM ".$table);
 if(!$rs)
 {
  return false;
 }
 foreach($rs AS $key=>$value)
 {
  $rslist[] = $value["Field"];
 }
 return $rslist;
 }
 #[显示表名]
 function list_tables()
 {
 $rs = $this->get_all("SHOW TABLES");
 return $rs;
 }
 function table_name($table_list,$i)
 {
 return $table_list[$i];
 }
 function escape_string($char)
 {
 if(!$char)
 {
  return false;
 }
 return mysqli_escape_string($this->conn,$char);
 }
 function get_version()
 {
 return mysqli_get_server_info($this->conn);
 }
 function time_used()
 {
 $time = explode(" ",microtime());
 $used_time = $time[0] + $time[1];
 return $used_time;
 }
 //Mysql的查询时间
 function conn_times()
 {
 return $this->conn_times + $this->query_times;
 }
 //MySQL查询资料
 function conn_count()
 {
 return $this->query_count;
 }
 # 高效SQL生成查询,仅适合单表查询
 function phpok_one($tbl,$condition="",$fields="*")
 {
 $sql = "SELECT ".$fields." FROM ".$this->db->prefix.$tbl;
 if($condition)
 {
  $sql .= " WHERE ".$condition;
 }
 return $this->get_one($sql);
 }
 function debug()
 {
 if(!$this->querylist || !is_array($this->querylist) || count($this->querylist) < 1)
 {
  return false;
 }
 $html = '<table cellpadding="0" cellspacing="0" width="100%" bgcolor="#CECECE"><tr><td>';
 $html.= '<table cellpadding="1" cellspacing="1" width="100%">';
 $html.= '<tr><th bgcolor="#EFEFEF" height="30px">SQL</th><th bgcolor="#EFEFEF" width="80px">查询</th></tr>';
 foreach($this->querylist AS $key=>$value)
 {
  $html .= '<tr><td bgcolor="#FFFFFF"><div style="padding:3px;color:#6E6E6E;">'.$value['sql'].'</div></td>';
  $html .= '<td align="center" bgcolor="#FFFFFF"><div style="padding:3px;color:#000000;">'.$value["count"].'</div></td></tr>';
 }
 $html.= "</table>";
 $html.= "</td></tr></table>";
 return $html;
 }
 function conn_status()
 {
 if(!$this->conn) return false;
 return true;
 }
}
>
 
标签: PHP mysqli 连接
反对 0举报 0 评论 0
 

免责声明:本文仅代表作者个人观点,与乐学笔记(本网)无关。其原创性以及文中陈述文字和内容未经本站证实,对本文以及其中全部或者部分内容、文字的真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
    本网站有部分内容均转载自其它媒体,转载目的在于传递更多信息,并不代表本网赞同其观点和对其真实性负责,若因作品内容、知识产权、版权和其他问题,请及时提供相关证明等材料并与我们留言联系,本网站将在规定时间内给予删除等相关处理.

  • php-fpm进程管理的三种模式 phpfpm子进程
    php-fpm进程管理的三种模式 phpfpm子进程
    php-fpm解读-进程管理的三种模式—程序媛大丽标明转载以示尊重 感谢原作者的分享。php-fpm进程管理一共有三种模式:ondemand、static、dynamic,我们可以在同一个fpm的master配置三种模式,看下图1。php-fpm的工作模式和nginx类似,都是一个master,多个worke
    03-08
  • nginx和php-fpm 是使用 tcp socket 还是 unix s
    tcp socket允许通过网络进程之间的通信,也可以通过loopback进行本地进程之间通信。unix socket允许在本地运行的进程之间进行通信。分析从上面的图片可以看,unix socket减少了不必要的tcp开销,而tcp需要经过loopback,还要申请临时端口和tcp相关资源。但是
    03-08
  • [PHP8] 我参加了PHP8工程师认证初学者考试beta考试
    [PHP8] 我参加了PHP8工程师认证初学者考试beta
    前几天,2022/08/05,PHP工程师认证机构PHP8 技术员认证初级考试宣布实施考试将于 2023 年春季开始。和 beta 测试完成于 2022/09/11所以我收到了。一般社团法人BOSS-CON JAPAN(代表理事:Tadashi Yoshimasa,地点:东京都世田谷区,以下简称“BOSS-CON JAPAN
    03-08
  • 将 PHP Insights 放入旧版 PJ 不是很好吗?谈论
    将 PHP Insights 放入旧版 PJ 不是很好吗?谈论
    介绍在最近的PHP系统开发中,感觉故事在理所当然包含静态分析工具的前提下进行。我的周围现有代码很脏,我很久以前安装了工具,但几乎没有检查已经观察到许多这样的案例。 (这是小说。而不是像 0 或 100 这样不允许单行错误的静态分析,一点一点,逐渐我想介
    03-08
  • PHP基于elasticsearch全文搜索引擎的开发 php使
    1.概述:全文搜索属于最常见的需求,开源的 Elasticsearch (以下简称 Elastic)是目前全文搜索引擎的首选。Elastic 的底层是开源库 Lucene。但是,你没法直接用 Lucene,必须自己写代码去调用它的接口。Elastic 是 Lucene 的封装,提供了 REST API 的操作接
    02-09
  • php视图操作
    一、视图的基本介绍         视图是虚拟的表。与包含数据的表不一样,视图只包含使用时动态检索数据的查询。        使用视图需要MySQL5及以后的版本支持。        下面是视图的一些常见应用:        重用SQL语句;        简化复杂的S
    02-09
  • php中图像处理的常用函数 php图形图像处理技术
    php中图像处理的常用函数 php图形图像处理技术
    1.imagecreate()函数imagecreate()函数是基于一个调色板的画布。?php $im = imagecreate(200,80);                //创建一个宽200,高80的画布。$white = imagecolorallocate($im,225,35,180);     //设置画布的背景颜色imagegif($im);
    02-09
  • PHP安全之webshell和后门检测
    PHP安全之webshell和后门检测
    基于PHP的应用面临着各种各样的攻击:XSS:对PHP的Web应用而言,跨站脚本是一个易受攻击的点。攻击者可以利用它盗取用户信息。你可以配置Apache,或是写更安全的PHP代码(验证所有用户输入)来防范XSS攻击SQL注入:这是PHP应用中,数据库层的易受攻击点。防范
    02-09
  • php使用时间戳保存时间的意义 PHP获取时间戳
    时间戳记录的是格林尼治时间,使用date格式化的时候会根据你程序设置的不同时区显示不同的时间。如果使用具体时间,则还需要进行多一步转换。
    02-09
  • PHP 获取提交表单数据方法
    PHP $_GET 和 $_POST变量是用来获取表单中的信息的,比如用户输入的信息。PHP表单操作在我们处理HTML表单和PHP表单时,我们要记住的重要一点是:HTML页面中的任何一个表单元素都可以自动的用于PHP脚本:表单举例: htmlbodyform action="welcome.php" method
    02-09
点击排行