自己写的PHP的mql类

用类封装的一个数据库的操作,不仅安全,而且会省去很多代码。

 1 header('Content-type:text/html;charset="utf-8"');
 2 class mysql{    
 3     /*下面是私有字段*/
 4     private $host;      //表示mysql服务器
 5     private $user;      //表示用户名
 6     private $pass;      //表示密码
 7     private $database;  //表示数据库名
 8     private $charset;   //表示字符集
 9     
10     /*私有方法:连接数据库*/
11     private function _connect(){
12         if(!mysql_connect($this->host,$this->user,$this->pass)){
13             exit('连接数据库服务器失败!');
14         }
15         mysql_select_db($this->database);
16         mysql_query("SET NAMES $this->charset");
17     }
18     
19     /*析构方法:赋值给私有字段*/
20     public function __construct($_host,$_user,$_pass,$_database,$_charset){
21         $this->host= $_host;    
22         $this->user= $_user;
23         $this->pass= $_pass;
24         $this->database= $_database;
25         $this->charset= $_charset;    
26         $this->_connect();    
27     }
28 
29     /*查询sql语句的方法*/
30     public function select($sql,$table){ 
31         $select = mysql_query("SELECT $sql From $table");    
32         return $select;        
33     }
34     
35     /*返回关联数组*/
36     public function my_fetch_arr($_result,$result_type){        
37         $rows = mysql_fetch_array($_result,$result_type);
38         return $rows;
39     }
40     
41     /*插入sql语句的方法*/
42     public function insert($table,$col,$value){
43         if (!mysql_query("INSERT INTO $table($col)values($value)")){
44             exit('插入数据时出现错误!');
45         }
46     }
47     
48     /*更新sql语句的方法*/
49     public function update($table,$col,$new_value,$colm,$values){
50         if (!mysql_query("UPDATE $table SET $col=$new_value where $colm=$values")){
51             exit('更新数据时出现错误!');
52         }
53     }
54     
55     /*删除sql语句的方法*/
56     public function delete($table,$col,$values){
57         if (!mysql_query("DELETE FROM $table where $col=$values")){
58             exit('删除数据时出现错误!');
59         }
60     }
61     
62     
63     /*关闭连接方法*/
64     public function _close(){
65         mysql_close();
66     }
67     
68 }
69 //类的实例化,且运行了析构方法__construct();
70 $mysql = new mysql("localhost","root","chang123","school","UTF8");  
71 
72 //执行了查询语句并将结果赋给$_result
73 $_result = $mysql->select("*","grade");
74 //返回从结果集中取的一行生成的关联数组或数字数组
75 $rows = $mysql->my_fetch_arr($_result,MYSQL_ASSOC);
76 
77 //关闭数据库连接
78 $mysql->_close();

 

posted on 2013-08-27 23:17  沉淀思潮  阅读(359)  评论(0编辑  收藏  举报

导航