我一直在尝试通过 CodeIgniter Controller 将数据插入数据库。我已经进行了验证过程并通过 ajax 响应接收验证错误。但似乎在表单中所有字段都已填写,之后如果我单击任何输入字段,甚至无需单击表单中的“保存”或“提交”按钮,就会插入数据。
因此,如果我按“名称”字段、“颜色”字段或“价格”字段,则会插入数据,而无需按“保存汽车”按钮。
**我的控制器:CarModel.php **
<?php
class 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
<?php
class Car_model extends CI_Model {
public function create($formArray){
$this->db->insert('car_models',$formArray);
}
}
四季花海
当年话下