php資料庫寫入操作類

來源:互聯網
上載者:User

php教程資料庫教程寫入操作類

有三個類:

1 . 過濾輸入(輕量級的)

class input_filter

負責將參數,如$_GET,$_POST 這些過濾

傳回值類型為 數組,用作 made_sql 類的參數

2 . 轉換成SQL語句

class made_sql

參數的類型為數組和表名(字串),數組的鍵名為表的列名,值為插入值

傳回值類型為 字串 ,用作 mysql教程 ->query方法 的參數

3 . 資料庫查詢

class mysql 

用到了單列模式,用靜態方法來擷取對象,具體參看 instanceof操作符的作用

 


 1   class input_filter
 2   {
 3  
 4        private $input_all; // 要過濾的數組
 5        private $rustle;     // 過濾後的結果
 6       
 7       //建構函式 參數可以是$_GET or $_POST 這些
 8       public function __construct($input_C)
 9       {
10           if(is_array($input_C))
11                $this->input_all = $input_C ;
12           else
13                echo 'Parameter is not valid';
14          
15           //初始化,不然後面第一次合并數組PHP不知道這是什麼類型     
16           $this->rustle = array(); 
17       }
18       
19       private function filter_arr()  // 主函數
20       {
21          
22           foreach ($this->input_all as  $key_input => $val_input)
23           {
24               //如果鍵名不是字串,那麼返回錯誤資訊
25               // for key
26               if(!is_string($key_input))  // error
27                  {
28                    echo 'This key is not string';
29                    return false;
30                  }
31               // The # is mysql Note . 
32               $key_one = str_replace('#','',$key_input);
33               $key = htmlspecialchars($key_one,ENT_QUOTES,'UTF-8');
34               
35               // 我沒找 # 的HTML轉義符,所以用空代替
37               $val_one = str_replace('#','',$val_input);
38               // 這個函數只轉化 < > ' "  ,還有個類似函數會轉義所有符號
39               $val = htmlspecialchars($val_one,ENT_QUOTES,'UTF-8');
40              
41               // merger     
42               $rustle_one = array($key=>$val);
43               //合并數組
44               $this->rustle = array_merge($this->rustle,$rustle_one);
45           }
46          
47       }
48      
49       //這個函數有點多餘,留下以後擴充用
50       public function get_filter_rustle()
51       {
52           $this->filter_arr();
53           return  $this->rustle ;
54       }
55
56   }

 

調用方法: 

  $filter = new filter_input($_GET) ; // or $_POST
  $input_data = $filter->get_filter();

 

 

轉換成SQL語句:

 1   class madesql
 2   {
 3       private $Cnow_ary;   // type array  傳入的參數
 4       private $Cname_str;
 5      
 6       private $insert_sql;  //最終的sql語句  string type
 7      
 8     
 9
10
11      
12       public function  __construct($Cary,$Cname)
13       {
14          //檢查傳入參數類型是否為數組
15          if (! is_array($Cary)) 
16              return false;
17          else
18              $this->Cnow_ary = $Cary;  // 寫入的值
19       
20          $this->Cname_str = $Cname;  // 資料庫表名稱
21        

25       }
26      
27       private function setSql()  // 主函數 ,生產SQL語句
28       {
29  
30            foreach ( $this->Cnow_ary as  $key_ary => $val_ary )
31            {
32                $cols_sql = $cols_sql.','.$key_ary; //列名組合
33                $vals_sql = $vals_sql.', ''.$val_ary.''' ; //值 組合
34            }
35             // 因為前面foreach的演算法有點問題,第一個字元是逗號
36             // 所以用sunstr_replace()刪除 ,自第一位起(0),只替換一個字元(1)   
37             $cols_sql = substr_replace($vals_sql,'',0,1);  
38             $vals_sql = substr_replace($vals_sql,'',0,1);
39             
40             $this->insert_sql =
41             'INSERT INTO '.$this->Cname_str.' ( '
42                                .$cols_sql.' ) VALUES ( '.$vals_sql.' )'; // 語句成型
43       }
44       //擴充用
45       public function getSql()
46       {
47           $this->setSql();
48           return $this->insert_sql;
49       }
50      
51    }

 

 

3 . 資料庫查詢

資料庫查詢類是參照書上的單列模式(用靜態方法擷取對象,這樣在一個指令碼裡只有一個資料庫查詢類的執行個體)

我想單例模式用於這個類還是有點用的

 1   class mysql
 2    {
 3        private $connect;
 4        static  $objectMysql; // 存放對象
 5       
 6        private function  __construct() 

 7        {   
 8           // 建立對象的時候這個建構函式會被調用,用來初始化
 9           $connect = mysql_connect('db address','password','dbname');
10           $this->db = mysql_select_db('db',$connect);   
11        }
12
13        public static function Mysql_object()
14        {   
15            //instanceof 操作符用於檢查對象是否屬於某個類或者介面的執行個體。我說的不是很規範...
16           //如果$objectMysql不是mysql(self)的執行個體,那麼就建立一個
17            if(! self::$objectMysql instanceof self)
18                 self::$objectMysql = new mysql();
19
20            //這時候的$objectMysql就已經是一個對象
21            return self::$objectMysql;  
22        }
23        public function query($sql)
24        {
25            return mysql_query($sql,$this->db);
26        }
27 
28   }

 

 

 

All right ,歸納一下使用方法

 

 1   $filter = new filter_input($_GET) ; // or $_POST http://www.111cn.net
 2   $input_data = $filter->get_filter();
 3  
 4   $madeSql = new madesql($input_data,'tableName');
 5   $sql = $madeSql->getSql();
 6
 7   $mysql = mysql::Mysql_object() ;
 8   if( $mysql->query($sql) )
 9       echo 'Ok';
10   else
11       echo 'failure';

 

只需要這幾行調用代碼即可以完成寫入資料庫的操作

 

另外再說一下建構函式的私人公有問題,書上的mysql單例模式中建構函式是聲明為了private ,而沒有單例模式的類如此則會產生編譯錯誤,即 PHP 不能建立一個對象 ,查了下。

原因在於建立對象往往在類外面進行,這樣就產生了無法訪問建構函式的問題。 而單列模式是在自身類中建立對象,因此訪問private方法沒有限制。

原先以為單例模式只是防止建立相同的對象,現在看來單例模式可以將建構函式封裝起來,確實提高了安全性

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.