我一直在嘗試通過 CodeIgniter Controller 將數據插入數據庫。我已經進行了驗證過程并通過 ajax 響應接收驗證錯誤。但似乎在表單中所有字段都已填寫,之后如果我單擊任何輸入字段,甚至無需單擊表單中的“保存”或“提交”按鈕,就會插入數據。因此,如果我按“名稱”字段、“顏色”字段或“價格”字段,則會插入數據,而無需按“保存汽車”按鈕。**我的控制器:CarModel.php **<?phpclass CarModel extends CI_Controller{ public function index() { $this->load->view('car_model/list.php'); } public function showCreateForm() { $html = $this->load->view('car_model/create', '', true); $response['html'] = $html; echo json_encode($response); } public function saveModel() { $this->load->model('Car_model'); $this->load->library('form_validation'); $this->form_validation->set_rules('name', 'Name', 'required'); $this->form_validation->set_rules('color', 'Color', 'required'); $this->form_validation->set_rules('price', 'Price', 'required'); if ($this->form_validation->run() == true) { //save enteries to DB $formArray = array(); $formArray['name'] = $this->input->post('name'); $formArray['color'] = $this->input->post('color'); $formArray['transmission'] = $this->input->post('transmission'); $formArray['price'] = $this->input->post('price'); $formArray['created_at'] = date('Y-m-d H:i:s'); $this->Car_model->create($formArray); $response['status'] = 1; } else { $response['status'] = 0; $response['name'] = strip_tags(form_error('name')); $response['color'] = strip_tags(form_error('color')); $response['price'] = strip_tags(form_error('price')); } echo json_encode($response); }}我的模型:Car_model.php<?phpclass Car_model extends CI_Model { public function create($formArray){ $this->db->insert('car_models',$formArray); }}
- 2 回答
- 0 關注
- 191 瀏覽
添加回答
舉報
0/150
提交
取消