1 <?php
  2  /**
  3  *数据库操作类
  4  *varsion:1.1
  5  *@param string 主机地址
  6  *@param string 用户名
  7  *@param string 密码
  8  *@param string 数据库名称
  9  *@param string 数据库编码
 10  *@param string 连接方式(conn、pconn)
 11  */
 12  class Mysql {
 13 
 14     protected $db_host;                        //主机地址
 15 
 16     protected $db_name;                        //数据库名
 17 
 18     protected $db_user;                        //数据库用户名
 19 
 20     protected $db_pwd;                            //数据库密码
 21 
 22     protected $db_charset;                        //数据库编码选择
 23 
 24     protected $conn;                            //连接标识
 25 
 26     protected $result;                            //执行sql后返回的结果
 27 
 28     protected $sql;                            //sql语句
 29 
 30     protected $prefix;                            //数据库表前缀
 31 
 32     /**
 33      *是否在操作界面开启错误提示,默认开启
 34      */
 35     public $error_show=true;
 36 
 37     /**
 38      *是否开启错误日志记录,默认开启
 39      */
 40     public $error_wirte=true;
 41 
 42     /**
 43      *错误日志保存位置,目录形式例如:/error/
 44      */
 45     public $error_file="/error/";
 46 
 47     /**
 48      *出现错误终止操作,错误后面的代码不在执行
 49      */
 50     public $error_stop=false;
 51 
 52     /**
 53      *构造函数
 54      *@param string 主机
 55      *@param string 用户名
 56      *@param string 密码
 57      *@param string 数据库名
 58      *@param string 编码
 59      *@param string 连接(pconn永久连接)
 60      */
 61     public function __construct($db_host,$db_user,$db_pwd,$db_name,$db_charset="GBK",$conn=""){
 62 
 63         $this->db_host=$db_host;
 64 
 65         $this->db_name=$db_name;
 66 
 67         $this->db_user=$db_user;
 68 
 69         $this->db_pwd=$db_pwd;
 70 
 71         $this->db_charset=$db_charset;
 72 
 73         $this->conn=$conn;
 74     }
 75     /**
 76     *数据库连接
 77     */
 78     public function connect(){
 79 
 80         if($this->conn=='pconn'){
 81 
 82             //永久连接
 83 
 84             $this->conn=mysql_connect($this->db_host,$this->db_user,$this->db_pwd);
 85         }
 86         else
 87         {
 88             //即时性连接
 89 
 90             $this->conn=mysql_pconnect($this->db_host,$this->db_user,$this->db_pwd);
 91         }
 92         if(!mysql_select_db($this->db_name,$this->conn)){
 93 
 94             $this->show_error("数据库连接失败!",$this->db_name);
 95         }
 96         mysql_query("set names $this->db_charset");//设置数据库编码
 97     }
 98     /**
 99      *选择数据库
100      */
101     public function select_db($dbname){
102 
103         return mysql_select_db($dbname);
104     }
105 
106     /**
107      *sql语句执行函数
108      */
109     public function query($sql){
110 
111         if(!$sql){
112 
113             $this->show_error("查询语句为空!","");
114         }
115         else{
116 
117             $this->sql=$this->strtrprefix($sql);
118 
119             $this->result=mysql_query($this->sql,$this->conn);
120 
121             if(!$this->result){
122 
123                 $this->show_error("sql语句错误",$this->sql);
124             }
125         }
126         return $this->result;
127     }
128 
129     /**
130      * 获取表内所有数据,返回数据库对象
131      * @access public
132      * @param string $table
133      * @return rs
134      */
135     public function findall($table){
136 
137          return  $this->query("select * from $table");
138     }
139     /**
140      * 简化查询语句,返回数据库对象
141      * @param string 表名
142      * @param string 查询条件
143      * @param string 字段,默认全部字段
144      * @param string 跳转地址
145      */
146      public function select($table,$condition,$field="*",$url=""){
147 
148            $this->query("select $field from $table where $condition");
149 
150            if (!empty ($url)and!empty($this->result)){
151 
152             $this->get_admin_msg($url,"查询成功!");
153            }
154 
155         return $this->result;
156      }
157      /**
158       *循环输出查询到的数据库对象
159       */
160      public function fetch_array($result=""){
161 
162          if(!empty($result))
163 
164             return  mysql_fetch_array($result);
165 
166          else
167 
168             return  mysql_fetch_array($this->result);
169      }
170 
171    /**
172     * 按照条件删除数据,返回影响条数
173     * @access public
174     * @param string 表名
175     * @param string 条件
176     * @param string 执行成功后调整url
177     * @return int 影响行数
178     */
179     public function delete($table,$condition,$url=""){
180 
181            $this->query("delete from $table where $condition");
182 
183            if (!empty ($url)){
184 
185                if(mysql_affected_rows())
186 
187                 $this->get_admin_msg($url,"删除成功!");
188 
189             else
190 
191                 $this->get_admin_msg($url,"没有数据被删除!");
192            }
193 
194            return mysql_affected_rows();
195     }
196    /**
197     *简化插入,返回影响条数
198     *@param string $table(表名)
199     *@param string $field(字段名)
200     *@param string $valude(内容)
201     *@param string $url(跳转地址)
202     */
203    public function insert($table,$field,$value,$url=""){
204 
205            $this->query("insert into $table ($field) values ($value)");
206 
207            if (!empty ($url)){
208 
209                if(mysql_affected_rows())
210 
211                  $this->get_admin_msg($url,"添加成功!");
212 
213             else
214 
215                  $this->get_admin_msg($url,"没有数据被添加!");
216            }
217 
218            return mysql_affected_rows();
219    }
220    /**
221     * 用一维数组形式插入数据,返回影响条数
222     * @access public
223     * @param string table
224     * @param array  数据数组
225     * @param string url
226     * @return int rows
227     */
228    public function insert_array($table,$array,$url=""){
229 
230            foreach($array as $filed=>$value){//数组转换字符串
231 
232                $fields=$fields.',`'.$filed.'`';
233 
234                $values=$values.',\''.$value.'\'';
235            }
236 
237         $fields=trim($fields,',');
238 
239         $values=trim($values,',');
240 
241            $this->query("insert into $table ($fields) values ($values)");
242 
243            if (!empty ($url)){
244 
245                if(mysql_affected_rows())
246 
247                  $this->get_admin_msg($url,"添加成功!");
248 
249             else
250 
251                  $this->get_admin_msg($url,"没有数据被添加!");
252            }
253            return mysql_affected_rows();
254    }
255    /**
256     *简化修改,返回影响条数
257     *@param string table
258     *@param string filed=value
259     *@param string condition
260     *@param string url
261     *@return int rows
262     */
263    public function update($table,$value,$condition,$url=""){
264 
265           $this->query("update $table set $value where $condition");
266 
267            if (!empty ($url)){
268 
269                if(mysql_affected_rows())
270 
271                  $this->get_admin_msg($url,"修改成功!");
272 
273             else
274 
275                  $this->get_admin_msg($url,"没有数据被修改!");
276            }
277            return mysql_affected_rows();
278    }
279    /**
280     *按照数组修改,返回影响条数
281     *
282     *@param string table
283     *
284     *@param array  filed=>value
285     *
286     *@param string condition
287     *
288     *@param string url
289     *
290     *@return int rows
291     */
292    public function update_array($table,$array,$condition,$url=""){
293 
294         foreach($array as $filed=>$value){//数组转换字符串
295 
296                $str=$str.",`".$filed."`='".$value."'";
297 
298            }
299 
300           $str=trim($str,',');
301 
302           $this->query("update $table set $str where $condition");
303 
304            if (!empty ($url)){
305 
306                if(mysql_affected_rows())
307 
308                  $this->get_admin_msg($url,"修改成功!");
309 
310             else
311 
312                  $this->get_admin_msg($url,"没有数据被修改!");
313            }
314 
315            return mysql_affected_rows();
316    }
317    /**
318     *返回最后操作数据库影响条数
319     */
320    public function rows(){
321 
322           return mysql_affected_rows();
323    }
324    /**
325     *最后插入ID
326     */
327    public function insertid(){
328 
329           return mysql_insert_id();
330    }
331     /**
332      * 错误输出、错误日志保存
333      */
334    public function show_error($message="",$sql=""){
335 
336         if($this->error_show){
337 
338            if(!$sql){
339 
340                 //非sql语句错误
341                 echo "错误提示:<font color=\"red\">".$message."</font>"."<br/>";
342 
343              }
344               else{
345                 //sql语句错误
346                 echo "<div class='mysql_error'>";
347 
348                 echo "<h3>数据库操作错误提示</h3>";
349 
350                 echo "<ul><li class='mesage'>".$message."</li>";
351 
352                 echo "<li class='error' >错误原因:" . mysql_error() . "</li>";
353 
354                 echo "<li class='sql'><pre>SQL:".$sql."</pre></li></ul></div>";
355              }
356         }
357         if($this->error_wirte){
358 
359                     //保存错误日期
360                     $ip=$this->getip();
361 
362                     $time=date("Y-m-d H:i:s");
363 
364                     $message="------------------------$time\r\n".$message;
365 
366                     $message=$message."\r\n$sql\r\n"."客户端:$ip\r\n"."时间:$time\r\n";
367 
368                     $filename=date("Y-m-d").".txt";
369 
370                     $file_dir=str_replace('\\', '/',dirname(dirname(__file__))).$this->error_file;
371 
372                     $file_path=$file_dir.$filename;
373 
374                     if(!file_exists($file_dir)){
375 
376                         if(!mkdir($file_dir)){
377 
378                             if($this->error_show) echo "创建目录".$this->error_file."失败";
379                         }
380                     }
381                     if(!file_exists($file_path)){
382 
383                         fopen($file_path,"w+");//创建文件
384                     }
385                     if(is_writable($file_path)){
386 
387                         if(!$handle=fopen($file_path,"a")){
388 
389                            if($this->error_show) echo "不能打开文件".$file_path;
390 
391                            exit;
392                         }
393                         if(!fwrite($handle,$message)){
394 
395                            echo $file_path."文件写入失败";
396 
397                             exit;
398                         }
399 
400                         fclose($handle);
401 
402                         if($this->error_show) echo "错误日志被保存在".$file_path;
403                     }
404                     else{
405 
406                         if($this->error_show) echo "文件".$filename."不可写入";
407                     }
408 
409          if($this->error_sotp) exit;
410         }
411     }
412 
413     /**
414      *获取客户端ip地址
415      */
416     public function getip(){
417 
418         if(!empty($_SERVER["HTTP_CLIENT_IP"]))
419 
420               $cip = $_SERVER["HTTP_CLIENT_IP"];
421 
422         else if(!empty($_SERVER["HTTP_X_FORWARDED_FOR"]))
423 
424               $cip = $_SERVER["HTTP_X_FORWARDED_FOR"];
425 
426         else if(!empty($_SERVER["REMOTE_ADDR"]))
427 
428               $cip = $_SERVER["REMOTE_ADDR"];
429         else
430 
431               $cip = "无法获取ip";
432         return $cip;
433     }
434     /**
435      * 返回mysql数据库基本信息
436      * 1:服务器信息,2:主机信息,3:协议信息,4:客户端信息
437      */
438     public function mysql_server($num=''){
439         switch ($num){
440 
441             case 1:
442                  return mysql_get_server_info();
443                  break;
444 
445             case 2:
446                  return mysql_get_host_info();
447                  break;
448 
449             case 3:
450                  return mysql_get_proto_info();
451                  break;
452 
453             case 4:
454                  return mysql_get_client_info();
455                  break;
456 
457             default:
458                  return mysql_get_client_info();
459                  break;
460         }
461     }
462     /**
463      * sql语句检测函数,防止sql注入
464      */
465      public function checksql($sql){
466 
467          $check = eregi('select|insert|update|delete|\'|\/\*|\*|\.\.\/|\.\/|union|into|load_file|outfile', $sql);
468 
469          if($check){
470 
471              $this->show_error("sql被拦截,请检测sql语句",$sql);
472 
473              return false;
474          }
475 
476          return $sql;
477      }
478     /**
479      * 释放数据库结果集
480      */
481     public function free(){
482 
483         @ mysql_free_result($this->result);
484     }
485     /**
486      * 处理表前缀
487      *
488      */
489     public function strtrprefix($sql){
490 
491         return strtr($sql,array("#@_"=>$this->prefix));
492 
493     }
494     /**
495     *(预留操作提示接口)执行成功跳转、提示函数
496     */
497     public function get_admin_msg($url, $msg) {}
498     /**
499      * 析构函数、释放结果关闭连接
500      */
501     public function __destruct(){
502 
503         if(!empty($this->result)){
504 
505             $this->free();
506         }
507 
508         @ mysql_close($this->conn);
509     }
510 }