数据库操作类是所有程序都可以实现的一个功能,下面我来分享一个PHP mysql数据库操作类,这个数据库操作类的特点是对所有保存到数据库的内容进入了过滤,可以很好的处理sql注入了,代码如下:
- <?php
-
- class db
- {
-
- var $db;
-
- var $position=0;
-
- function sub_sql($str)
- {
- global $prefix;
- return str_replace("#@__",$prefix,$str);
- }
- function Sql($str)
- {
- $str=$this->sub_sql($str);
- $result = mysql_query($str);
- $i=0;
- while($row = mysql_fetch_array($result))
- {
- $str_array[$i]=$row;
- $i++;
- }
- if(emptyempty($str_array))
- {
- $str_array=array();
- }
- $this->db=$str_array;
- }
-
- function Get_One()
- {
- $re=emptyempty($this->db[$this->position])?null:$this->db[$this->position];
- $this->position=$re?$this->position+1:$this->position;
- return $re;
- }
-
- function Judge()
- {
- $re=emptyempty($this->db[$this->position])?true:false;
- return $re;
- }
-
- function Get_Num()
- {
- return count($this->db);
- }
-
- function Set_Updata($t,$v,$w,$p=0)
- {
- $this->Sql($t);
- $v_str="";
- $w_str="";
- $f="";
- foreach($v as $key=>$vaule)
- {
- if(!is_numeric($key))
- {
- if(emptyempty($v_str))
- {
- $v_str=htmlspecialchars($key)."='".htmlspecialchars($vaule)."'";
- }else
- {
- $v_str=$v_str.",".htmlspecialchars($key)."='".htmlspecialchars($vaule)."'";
- }
- }
- }
- switch($p)
- {
- case 0:
- $f="=";
- break;
- case 1:
- $f=">";
- break;
- case -1:
- $f="<";
- break;
- }
- if(!emptyempty($f))
- {
- foreach($w as $key=>$vaule)
- {
- if(!is_numeric($key))
- {
- if(emptyempty($v_str))
- {
- $w_str=htmlspecialchars($key).$f.htmlspecialchars($vaule)."'";
- }else
- {
- $w_str=$w_str.",".htmlspecialchars($key).$f.htmlspecialchars($vaule)."'";
- }
- }
- }
- }
- $sql="UPDATE ".$t." SET ".$v_str." where ".$w_str;
- return $result = mysql_query($sql);
- }
-
- function Set_Del($t,$w,$p=0)
- {
- $this->sub_sql($t);
- $w_str="";
- $f="";
- switch($p)
- {
- case 0:
- $f="=";
- break;
- case 1:
- $f=">";
- break;
- case -1:
- $f="<";
- break;
- }
- if(!emptyempty($f))
- {
- foreach($w as $key=>$vaule)
- {
- if(!is_numeric($key))
- {
- if(emptyempty($v_str))
- {
- $w_str=htmlspecialchars($key).$f.htmlspecialchars($vaule)."'";
- }else
- {
- $w_str=$w_str.",".htmlspecialchars($key).$f.htmlspecialchars($vaule)."'";
- }
- }
- }
- }
- $str="DELETE FROM ".$t." WHERE ".$w_str;
- return $result = mysql_query($str);
- }
- function Add($t,$v)
- {
- $this->sub_sql($t);
- $k_str="";
- $v_str="";
- foreach($v as $key=>$vaule)
- {
- if(!is_numeric($key)){
- if(emptyempty($k_str))
- {
- $k_str=htmlspecialchars($key);
- $v_str="'".htmlspecialchars($vaule)."'";
- }else
- {
- $k_str=$k_str.",".htmlspecialchars($key);
- $v_str=$v_str.","."'".htmlspecialchars($vaule)."'";
- }
- }
- }
- $str="INSERT INTO ".$t."(".$k_str.")"."value(".$v_str.")";
- return $result = mysql_query($str);
- }
- }
- ?>
|