提交視圖頁面后,如果表單欄位不包含值,則應出現錯誤訊息,但在我的情況下,資料庫中插入了空值。所以請幫助我哪里出錯了。
如果表單欄位為空,則應執行 if 條件,然后查看頁面應顯示錯誤訊息,而不是執行 if 條件其執行其他代碼并在資料庫中插入空值。控制器
public function test_submit()
{
$this->load->library('form_validation');
$this->form_validation->set_rules('test_name', 'Test Name', 'trim|required|is_unique[add_test.TestName]');
$this->form_validation->set_rules('description', 'Description', 'trim|required');
$this->form_validation->set_rules('test_price', 'Test Price', 'trim|required');
$this->form_validation->set_rules('correct_answer', 'Corrent Answer', 'trim|required');
$this->form_validation->set_rules('wrong_answer', 'Wrong Answer', 'trim|required');
if ($this->form_validation->run() == FALSE)
{
$this->load->view('add_test_view');
}
$test_name=$this->input->post('test_name');
$description=$this->input->post('description');
$test_price=$this->input->post('test_price');
$correct_answer=$this->input->post('correct_answer');
$wrong_answer=$this->input->post('wrong_answer');
$insert_data = array(
'TestName' =>$test_name,
'Description' => $description,
'Price' => $test_price,
'CorrectAnswerMarks' => $correct_answer,
'WrongAnswerDeduction' => $wrong_answer
);
$result=$this->test_model->add_test($insert_data);
$this->session->set_tempdata('success', "Test with name ".$test_name." Is Added Successfully.","20");
redirect('testmodule/addtest', 'refresh');
}
uj5u.com熱心網友回復:
您應該在驗證的其他部分插入資料,如下所示:
if ($this->form_validation->run() == FALSE)
{
$this->load->view('add_test_view');
} else {
// Insert code should go here
}
這將確保只有在驗證成功時才插入資料。您應該使用validation_error() 函式來顯示如下錯誤訊息:
if ($this->form_validation->run() == FALSE){
$this->session->set_flashdata("error", validation_errors());
redirect('your_controller/your_function');
}
在上面所有由于驗證失敗而導致的錯誤都將顯示在視圖上。使用重定向還可以確保該函式的執行在那里停止。您必須在視圖中使用以下內容:
<div class="text-danger text-center text-bold"><b><?=$this->session->flashdata('error');?></b></div>
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/394472.html
