關於ci中的表單提交問題


codeIgniter是一種PHP開源框架,它會自帶一些表單驗證的功能,安全過濾等等。

這里的驗證字段對應的是網頁中的表單,而不是數據庫中的字段,這一點要認清楚了。可以通過

$this->load->library('form_validation');
來加載驗證輔助函數,通過

$this->form_validation->set_rules('username', 'Username', 'required');
來對username進行驗證,這里的username對應的是表單中的屬性,而不是數據庫中username。

if ($_POST) {
            //加載驗證輔助函數
            $this -> load -> helper(array('form', 'url'));
            $this -> load -> library('form_validation');
            //對表單進行過濾驗證處理
            $this->form_validation->set_rules('name', 'Name', 'trim|strip_tags|required|max_length[40]|xss_clean');
            $this->form_validation->set_rules('company', 'Company Name', 'trim|strip_tags|max_length[150]|xss_clean');
            $this->form_validation->set_rules('country', 'Country', 'trim|strip_tags|max_length[140]|xss_clean');
            $this->form_validation->set_rules('email', 'Email', 'trim|strip_tags|required|max_length[140]|xss_clean');
            $this->form_validation->set_rules('title', 'Title', 'trim|strip_tags|max_length[140]|xss_clean');
            $this -> form_validation -> set_rules('phone', 'Telephone', 'trim|strip_tags|max_length[40]|xss_clean');
            $this->form_validation->set_rules('desc', 'Message', 'trim|strip_tags|xss_clean');
            if ($this -> form_validation -> run() == FALSE) {
                  redirect($_SERVER['HTTP_REFERER']);
            } else {
                    //如果通過驗證,將獲取的數據保存
                    //獲取過濾后的數據
                    $name = $this -> input -> post('name');
                    $company = $this -> input -> post('company');
                    $email = $this -> input -> post('email');
                    $phone = $this -> input -> post('phone');
                    $country = $this -> input -> post('country');
                    $title = $this -> input -> post('title');
                    $desc = $this -> input -> post('desc');
                    if (!$title) {
                        $title = "a new contact message has been arrived";
                    }
                $data = array('name' => $name, 'company_name' => $company,
                'email' => $email, 'country' => $country, 'title' => $title,
                 'tel' => $phone, 'message' => $desc);
                $this -> db -> insert('contact', $data);
                $this->session->set_flashdata('contact_success', 'your request has been sent successfully,
                we will contact you via email in a short time!');
                redirect($_SERVER['HTTP_REFERER']);
                

            }

上面的代碼是對表單進行驗證的代碼,表單的字段與數據庫字段有一點點區別,對其進行驗證時,要以表單字段為基准。而且獲取數據,要在驗證之后獲取,否則保存的數據庫的信息,還是過濾之前的信息,比如有空格,比如有<br>等等。這是一個注意點。

要能夠正確的理解表單驗證的原理,編程的時候,才不會出錯。今天驗證電話時,我用的是數據庫中的字段tel,而不是表單中的字段phone,結果怎么用都沒有效果。非常苦惱。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM