表单缓存我的输入并在刷新页面时插入它如何阻止它 我应该使用CodeIgniter验证还是可以使用我的?
视图:
<html>
<head></head>
</body>
<?php echo validation_errors(); ?>
<?php echo form_open('speed/insert_to_db'); ?>
Branch: <input type="text" name="branch" /><br/>
Business Unit: <input type="text" name="buinessUnit" /><br/>
Device Type: <input type="text" name="deviceType" /><br/>
Brand: <input type="text" name="brand" /><br/>
Device Model: <input type="text" name="deviceModel" /><br/>
SN: <input type="text" name="SN" /><br/>
status: <input type="text" name="status" /><br/>
department: <input type="text" name="department" /><br/>
username: <input type="text" name="username" /><br/>
notes: <input type="textarea" name="notes" /><br/>
computername: <input type="text" name="computerName" /><br/>
Save:<input type="submit" name="save" />
</form>
控制器:
class Speed extends CI_Controller {
function insert_to_db()
{
//$this->output->enable_profiler(TRUE);
$this->load->model('add_model');
$this->add_model->insert_into_db();
$this->load->view('pages/home');//loading success view
}
}
模型:将数据插入数据库
<?php
class add_model extends CI_Model {
public function insert_into_db(){
$post=$this->input->post();
if(!isset($post['save'])) return;
$data=array('Branch'=>$post['branch'],'BusinessUnit'=>$post['buinessUnit'],'DeviceType'=>$post['deviceType'],'Brand'=>$post['brand'],'DeviceModel'=>$post['deviceModel'],'SN'=>$post['SN'],'Status'=>$post['status'],'Departmant'=>$post['department'],'UserName'=>$post['username'],'Notes'=>$post['notes'],'ComputerName'=>$post['computerName']);
$this->db->insert('hardware_assets', $data);
return $this->db->insert_id(); // if using mysql
}
}
答案 0 :(得分:0)
您可以为控制器生成如下代码的随机数,
$rand = rand( 100000, 999999);
$data['rand'] = $rand;
$this->session->set_userdata('form_hash',$rand);
当第一个控制器调用时,并将其传递给隐藏变量中的形式,如在视图中,
<input type="hidden" name="form_hash" value="<?php echo $rand?>" />
所以,每次控制器被调用时,如果它相同,则比较数字,如果验证通过,则继续,否则,不插入数据。
if($this->input->post('form_hash') == $this->session->userdata('form_hash'))
{
// process with database entry
}
请注意,这两个哈希只会匹配一次,而在第一次提交表单时,每隔一次,if条件将失败。
所以,你的最终代码将是这样的,
class Speed extends CI_Controller
{
function insert_to_db()
{
$this->load->model('add_model');
if($this->input->post('form_hash') == $this->session->userdata('form_hash'))
{
$this->add_model->insert_into_db();
}
$rand = rand( 100000, 999999);
$data['rand'] = $rand;
$this->session->set_userdata('form_hash',$rand);
//loading success view
$this->load->view('pages/home', $data);
}
}
并且不要忘记在表单中的视图中插入此行,
<input type="hidden" name="form_hash" value="<?php echo $rand?>" />