【问题标题】:how can i stop insert data when refresh page with codeigniter使用codeigniter刷新页面时如何停止插入数据
【发布时间】:2015-05-23 17:24:33
【问题描述】:

我需要在刷新页面时停止插入数据 我是codeigniter的新手,不能轻易重定向,请支持 view:pages/home.php 有一个表单的视图

<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>
</body>
</html>

模型:添加模型 具有 insert_to_db 功能的模型

       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
       }
}

控制器:

<?php

class Speed extends CI_Controller {

        function insert_to_db()
           {

             $this->load->model('add_model');

             $this->add_model->insert_into_db();
             $this->load->view('pages/home');//loading success view

           }


}

【问题讨论】:

    标签: php codeigniter


    【解决方案1】:

    使用 $this->input->post('input_name') 代替原始代码并检查控制器中的表单提交。即

    <?php
    
    class Speed extends CI_Controller {
    
        function insert_to_db()
           {
    
             $this->load->model('add_model');
             if($this->input->post('save')){
                $this->add_model->insert_into_db();
                $this->load->view('pages/home');//loading success view
             }
    
    
           }
    }
    

    同时从模型中删除 if(!isset($post['save'])) return;

    【讨论】:

    • 我的代码插入数据成功但是刷新时又插入了一个
    • 你测试过我的代码吗?除非您按“保存”按钮,否则它永远不会插入数据
    • 是的,刷新时仍然插入数据
    【解决方案2】:

    首先,我不会在模型中包含任何 $post$get 数据。使用 CI 可以做到这一点,但是,更标准的做法是在控制器中获取数据,对其进行验证,然后将其传递给模型。

    其次,查看Form Validation Library的文档

    它还提供了一些很好、简单的示例来说明如何处理表单提交。

    IMO 停止重新提交表单的最简单方法是在您从提交中获得所有数据后重定向。您可以使用 url_helper 文件中的 redirect() 函数来执行此操作。

    希望这会有所帮助!

    【讨论】:

      猜你喜欢
      • 2013-08-09
      • 1970-01-01
      • 1970-01-01
      • 2015-11-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多