一款简单实用的php操作mysql数据库类

这篇文章主要介绍了一款简单实用的php操作mysql数据库类,不但包含了php针对mysql数据库的常见操作之外,还有针对危险字符的过滤功能,非常具有实用价值,需要的朋友可以参考下

本文实例讲述了一款简单实用的php操作mysql数据库类。分享给大家供大家参考。具体如下:

  1. /*
  2. 本款数据库连接类,他会自动加载sql防注入功能,过滤一些敏感的sql查询关键词,同时还可以增加判断字段 show table status的性质与show table类 获取数据库所有表名等。*/
  3. @ini_set('mysql.trace_mode','off');
  4. class mysql
  5. {
  6. public $dblink;
  7. public $pconnect;
  8. private $search = array('/union(s*(/*.**/)?s*)+select/i', '/load_file(s*(/*.**/)?s*)+(/i', '/into(s*(/*.**/)?s*)+outfile/i');
  9. private $replace = array('union   select', 'load_file   (', 'into   outfile');
  10. private $rs;
  11. function __construct($hostname,$username,$userpwd,$database,$pconnect=false,$charset='utf8')
  12. {
  13. define('allowed_htmltags', '<html><embed><title><meta><body><a><p><br><hr><h1><h2><h3><h4><h5><h6><font><u><i><b><strong><div><span><ol><ul><li><img><table><tr><td><map>');
  14. $this->pconnect=$pconnect;
  15. $this->dblink=$pconnect?mysql_pconnect($hostname,$username,$userpwd):mysql_connect($hostname,$username,$userpwd);
  16. (!$this->dblink||!is_resource($this->dblink)) && fatal_error("connect to the database unsuccessfully!");
  17. @mysql_unbuffered_query("set names {$charset}");
  18. if($this->version()>'5.0.1')
  19. {
  20. @mysql_unbuffered_query("set sql_mode = ''");
  21. }
  22. @mysql_select_db($database) or fatal_error("can not select table!");
  23. return $this->dblink;
  24. }
  25. function query($sql,$unbuffered=false)
  26. {
  27. //echo $sql.'<br>';
  28. $this->rs=$unbuffered?mysql_unbuffered_query($sql,$this->dblink):mysql_query($sql,$this->dblink);
  29. //(!$this->rs||!is_resource($this->rs)) && fatal_error("execute the query unsuccessfully! error:".mysql_error());
  30. if(!$this->rs)fatal_error('在执行sql语句 '.$sql.' 时发生以下错误:'.mysql_error());
  31. return $this->rs;
  32. }
  33. function fetch_one($sql)
  34. {
  35. $this->rs=$this->query($sql);
  36. return dircms_strips教程lashes($this->filter_pass(mysql_fetch_array($this->rs,mysql_assoc)));
  37. }
  38. function get_maxfield($filed='id',$table) // 获取$table表中$filed字段的最大值
  39. {
  40. $r=$this->fetch_one("select {$table}.{$filed} from `{$table}` order by `{$table}`.`{$filed}` desc limit 0,1");
  41. return $r[$filed];
  42. }
  43. function fetch_all($sql)
  44. {
  45. $this->rs=$this->query($sql);
  46. $result=array();
  47. while($rows=mysql_fetch_array($this->rs,mysql_assoc))
  48. {
  49. $result[]=$rows;
  50. }
  51. mysql_free_result($this->rs);
  52. return dircms_stripslashes($this->filter_pass($result));
  53. }
  54. function fetch_all_withkey($sql,$key='id')
  55. {
  56. $this->rs=$this->query($sql);
  57. $result=array();
  58. while($rows=mysql_fetch_array($this->rs,mysql_assoc))
  59. {
  60. $result[$rows[$key]]=$rows;
  61. }
  62. mysql_free_result($this->rs);
  63. return dircms_stripslashes($this->filter_pass($result));
  64. }
  65. function last_insert_id()
  66. {
  67. if(($insertid=mysql_insert_id($this->dblink))>0)return $insertid;
  68. else //如果 auto_increment 的列的类型是 bigint,则 mysql_insert_id() 返回的值将不正确.
  69. {
  70. $result=$this->fetch_one('select last_insert_id() as insertid');
  71. return $result['insertid'];
  72. }
  73. }
  74. function insert($tbname,$varray,$replace=false)
  75. {
  76. $varray=$this->escape($varray);
  77. $tb_fields=$this->get_fields($tbname); // 升级一下,增加判断字段是否存在
  78. foreach($varray as $key => $value)
  79. {
  80. if(in_array($key,$tb_fields))
  81. {
  82. $fileds[]='`'.$key.'`';
  83. $values[]=is_string($value)?'''.$value.''':$value;
  84. }
  85. }
  86. if($fileds)
  87. {
  88. $fileds=implode(',',$fileds);
  89. $fileds=str_replace(''','`',$fileds);
  90. $values=implode(',',$values);
  91. $sql=$replace?"replace into {$tbname}({$fileds}) values ({$values})":"insert into {$tbname}({$fileds}) values ({$values})";
  92. $this->query($sql,true);
  93. return $this->last_insert_id();
  94. }
  95. else return false;
  96. }
  97. function update($tbname, $array, $where = '')
  98. {
  99. $array=$this->escape($array);
  100. if($where)
  101. {
  102. $tb_fields=$this->get_fields($tbname); // 增加判断字段是否存在
  103. $sql = '';
  104. foreach($array as $k=>$v)
  105. {
  106. if(in_array($k,$tb_fields))
  107. {
  108. $k=str_replace(''','',$k);
  109. $sql .= ", `$k`='$v'";
  110. }
  111. }
  112. $sql = substr($sql, 1);
  113. if($sql)$sql = "update `$tbname` set $sql where $where";
  114. else return true;
  115. }
  116. else
  117. {
  118. $sql = "replace into `$tbname`(`".implode('`,`', array_keys($array))."`) values('".implode("','", $array)."')";
  119. }
  120. return $this->query($sql,true);
  121. }
  122. function mysql_delete($tbname,$idarray,$filedname='id')
  123. {
  124. $idwhere=is_array($idarray)?implode(',',$idarray):intval($idarray);
  125. $where=is_array($idarray)?"{$tbname}.{$filedname} in ({$idwhere})":" {$tbname}.{$filedname}={$idwhere}";
  126. return $this->query("delete from {$tbname} where {$where}",true);
  127. }
  128. function get_fields($table)
  129. {
  130. $fields=array();
  131. $result=$this->fetch_all("show columns from `{$table}`");
  132. foreach($result as $val)
  133. {
  134. $fields[]=$val['field'];
  135. }
  136. return $fields;
  137. }
  138. function get_table_status($database)
  139. {
  140. $status=array();
  141. $r=$this->fetch_all("show table status from `".$database."`"); /////// show table status的性质与show table类似,不过,可以提供每个表的大量信息。
  142. foreach($r as $v)
  143. {
  144. $status[]=$v;
  145. }
  146. return $status;
  147. }
  148. function get_one_table_status($table)
  149. {
  150. return $this->fetch_one("show table status like '$table'");
  151. }
  152. function create_fields($tbname,$fieldname,$size=0,$type='varchar') // 2010-5-14 修正一下
  153. {
  154. if($size)
  155. {
  156. $size=strtoupper($type)=='varchar'?$size:8;
  157. $this->query("alter table `{$tbname}` add `$fieldname` {$type}( {$size} ) not null",true);
  158. }
  159. else $this->query("alter table `{$tbname}` add `$fieldname` mediumtext not null",true);
  160. return true;
  161. }
  162. function get_tables() //获取所有表表名
  163. {
  164. $tables=array();
  165. $r=$this->fetch_all("show tables");
  166. foreach($r as $v)
  167. {
  168. foreach($v as $v_)
  169. {
  170. $tables[]=$v_;
  171. }
  172. }
  173. return $tables;
  174. }
  175. function create_model_table($tbname) //创建一个内容模型表(start:初始只有字段contentid int(20),用于内容表,/////////////////////// update:2010-5-20 默认加入`content` mediumtext not null,字段)
  176. {
  177. if(in_array($tbname,$this->get_tables())) return false; ///////////////////// 当表名已经存在时,返回 false
  178. if($this->query("create table `{$tbname}` (
  179. `contentid` mediumint(8) not null ,
  180. `content` mediumtext not null,
  181. key ( `contentid` )
  182. ) engine = myisam default charset=utf8",true))return true; //////////////////// 成功则返回 true
  183. return false; //////////////失败返回 false
  184. }
  185. function create_table($tbname) //创建一个会员模型空表(初始只有字段userid int(20),用于会员表,2010-4-26)
  186. {
  187. if(in_array($tbname,$this->get_tables())) return false;
  188. if($this->query("create table `{$tbname}` (
  189. `userid` mediumint(8) not null ,
  190. key ( `userid` )
  191. ) engine = myisam default charset=utf8",true))return true;
  192. return false;
  193. }
  194. function escape($str) // 过滤危险字符
  195. {
  196. if(!is_array($str)) return str_replace(array('n', 'r'), array(chr(10), chr(13)),mysql_real_escape_string(preg_replace($this->search,$this->replace, $str), $this->dblink));
  197. foreach($str as $key=>$val) $str[$key] = $this->escape($val);
  198. return $str;
  199. }
  200. function filter_pass($string, $allowedtags = '', $disabledattributes = array('onabort', 'onactivate', 'onafterprint', 'onafterupdate', 'onbeforeactivate', 'onbeforecopy', 'onbeforecut', 'onbeforedeactivate', 'onbeforeeditfocus', 'onbeforepaste', 'onbeforeprint', 'onbeforeunload', 'onbeforeupdate', 'onblur', 'onbounce', 'oncellchange', 'onchange', 'onclick', 'oncontextmenu', 'oncontrolselect', 'oncopy', 'oncut', 'ondataavaible', 'ondatasetchanged', 'ondatasetcomplete', 'ondblclick', 'ondeactivate', 'ondrag', 'ondragdrop', 'ondragend', 'ondragenter', 'ondragleave', 'ondragover', 'ondragstart', 'ondrop', 'onerror', 'onerrorupdate', 'onfilterupdate', 'onfinish', 'onfocus', 'onfocusin', 'onfocusout', 'onhelp', 'onkeydown', 'onkeypress', 'onkeyup', 'onlayoutcomplete', 'onload', 'onlosecapture', 'onmousedown', 'onmouseenter', 'onmouseleave', 'onmousemove', 'onmoveout', 'onmouseo教程ver', 'onmouseup', 'onmousewheel', 'onmove', 'onmoveend', 'onmovestart', 'onpaste', 'onpropertychange', 'onreadystatechange', 'onreset', 'onresize', 'onresizeend', 'onresizestart', 'onrowexit', 'onrowsdelete', 'onrowsinserted', 'onscroll', 'onselect', 'onselectionchange', 'onselectstart', 'onstart', 'onstop', 'onsubmit', 'onunload'))
  201. {
  202. if(is_array($string))
  203. {
  204. foreach($string as $key => $val) $string[$key] = $this->filter_pass($val, allowed_htmltags);
  205. }
  206. else
  207. {
  208. $string = preg_replace('/s('.implode('|', $disabledattributes).').*?([s>])/', '', preg_replace('/<(.*?)>/ie', "'<'.preg_replace(array('/网页特效:[^"']*/i', '/(".implode('|', $disabledattributes).")[ ]*=[ ]*["'][^"']*["']/i', '/s+/'), array('', '', ' '), stripslashes('')) . '>'", strip_tags($string, $allowedtags)));
  209. }
  210. return $string;
  211. }
  212. function drop_table($tbname)
  213. {
  214. return $this->query("drop table if exists `{$tbname}`",true);
  215. }
  216. function version()
  217. {
  218. return mysql_get_server_info($this->dblink);
  219. }
  220. }

希望本文所述对大家的PHP程序设计有所帮助。