获取最后一个插入ID并将数组或多个值保存到mysql数据库codeigniter中

时间:2017-12-28 16:36:02

标签: php mysql codeigniter

我真的需要你的帮助我已经工作了几个星期,我有一个动态字段是一个名为' size'并且有一个名为“' category'”的字段,每个类别都有一个或多个大小。现在我需要将数据保存到两个表中。类别和大小彼此相关,在这里:

(我的数据库表)

CREATE TABLE `category` (
  `category_id` int(11) NOT NULL AUTO_INCREMENT,
  `category_name` varchar(55) NOT NULL,
  PRIMARY KEY (`category_id`)
) 
CREATE TABLE `sizes` (
  `size_id` int(11) NOT NULL AUTO_INCREMENT,
  `size` varchar(45) NOT NULL,
  `category_id` int(11) NOT NULL,
  PRIMARY KEY (`size_id`),
  KEY `cat_fk_idx` (`category_id`),
  CONSTRAINT `cat_fk` FOREIGN KEY (`category_id`) REFERENCES `category` (`category_id`) ON DELETE NO ACTION ON UPDATE NO ACTION
) 

这是我的观点(category.php)

<div class="col-sm-5">
<?php echo $this->session->flashdata('errorMessage');?>
<?php echo $this->session->flashdata('successMessage');?>
<?php echo form_open('category_con/add_category'); ?>
<?php echo form_fieldset('<h1 class="text-danger">Categories</h1>'); ?>
<div class="form-group">
    <label for='Username'>Add New Category</label>
    <input type="text" name="category_name" class="form-control" placeholder="Add new Category here">
</div>



    <script src="assets/js/jquery.min.js"></script>  

                    <div class="form-group">  
                         <form name="add_name" id="add_name">  
                              <div class="table-responsive">  
                                   <table class="table table-bordered" id="dynamic_field">  
                                        <tr>  
                                             <td><input type="text" name="size[]" placeholder="Add Size" class="form-control name_list" /></td>  
                                             <td><button type="button" name="add" id="add" class="btn btn-success">Add More</button></td>  
                                        </tr>  
                                   </table>  

                              </div>  
                         </form>  
                    </div>  
      <div class="form-group">
        <input type="submit" name="save_category" class="btn btn-success" value="Save Category">
    </div>           
    </div>  

     <script>  
     $(document).ready(function(){  
          var i=1;  
          $('#add').click(function(){  
               i++;  
               $('#dynamic_field').append('<tr id="row'+i+'"><td><input type="text" name="size[]" placeholder="Add Size" class="form-control name_list" /></td><td><button type="button" name="remove" id="'+i+'" class="btn btn-danger btn_remove">X</button></td></tr>');  
          });  
          $(document).on('click', '.btn_remove', function(){  
               var button_id = $(this).attr("id");   
               $('#row'+button_id+'').remove();  
          });  

     });  
     </script>


    <?php echo form_close(); ?>

我的控制器(category_con.php)

public function add_category( ) {
        $this->form_validation->set_rules('category_name', 'Category', 'required|alpha');


        if ($this->form_validation->run() == FALSE) {
            $this->session->set_flashdata('errorMessage', '<div class="alert alert-danger"> '.validation_errors() . '</div>');
            redirect(base_url('categories'));
        }else {

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


            $exec = $this->categories_model->categorysize();
            if ($exec) {
                $this->session->set_flashdata('successMessage', '<div class="alert alert-success"> Category Added Successfully</div>');
                redirect(base_url('categories'));
            }else {
                $this->session->set_flashdata('errorMessage', '<div class="alert alert-danger">Opps... Something Went Wrong Please Try Again.</div>' );
            redirect(base_url('categories'));

                        }

        }
    }

我的模型(categories_model.php)

public function categorysize()
    {
       $this->load->database();
       $category_name = $this->input->post('category_name');



     $this->db->query("INSERT INTO category (category_name) VALUES (".$this->db->escape($category_name).")");

        $last_row_id = $this->db->insert_id();  // Gets last row id ( category_id )
for($i = 0; $i < count ($_POST['size']); $i++){
        $form_data[] = array(

                'size'        => $_POST['size'][$i] ,
                'category_id' => "$last_row_id"

        );


        $this->db->insert_batch('sizes', $form_data);

    }
    }

单击保存按钮后,它会将类别保存在类别表中,大小将保存在sizes表和category_id上,但第一个输入将重复。并且它显示错误消息&#34; Opps ...有些错误请再试一次&#34;我把它放在我的控制器上,但是如果我删除了错误消息,即使我重定向页面,我也有一个blnk页面。

我希望你能帮助我。谢谢!!

1 个答案:

答案 0 :(得分:0)

我相信以下内容会有所帮助。一,模型。它需要返回Controller可以使用的东西。

class Categories_model extends CI_Model
{

    public function __construct()
    {
        parent::__construct();
        $this->load->database(); //Or do this in autoload.php
    }

    public function categorysize()
    {
        $category_name = $this->input->post('category_name');

        // using insert() like this will automatically escape $category_name
        $this->db->insert("category", ['category_name' => $category_name]);

        $last_row_id = $this->db->insert_id();  // Gets last row id ( category_id )

        $form_data = []; //empty array, just in case

        $sizes = $this->input->post('size'); //safer than using $_POST directly
        foreach($sizes as $size)
        {
            $form_data[] = array('size' => $size, 'category_id' => "$last_row_id");
        }

        // insert_batch() returns number of rows inserted or FALSE on failure
        // so the next line will return TRUE as long as insert_batch() doesn't return FALSE
        return FALSE !== $this->db->insert_batch('sizes', $form_data);
    }

}

在控制器中,您现在可以从模型返回以使用if语句进行测试

public function add_category()
{
    $this->form_validation->set_rules('category_name', 'Category', 'required|alpha');

    if($this->form_validation->run() === FALSE) //use the explicit comparison operator ===
    {
        $this->session->set_flashdata('errorMessage', '<div class="alert alert-danger"> '.validation_errors().'</div>');
        redirect(base_url('categories'));
    }
    // You don't need an else block because the if block ends the script when it runs 
    // Script is ended by redirect() which does not return to this code

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

    if($this->categories_model->categorysize())
    {
        $this->session->set_flashdata('successMessage', 
            '<div class="alert alert-success"> Category Added Successfully</div>');
    }
    else
    {
        $this->session->set_flashdata('errorMessage',
            '<div class="alert alert-danger">Opps... Something Went Wrong Please Try Again.</div>');
    }
    redirect(base_url('categories'));
}

以下内容不会影响输出,但会减少您必须执行的输入操作。任何时候你连续有几个php命令,你不需要用<?php ?>标签包围它们。然后,在您的视图中围绕所有行,就像这样

<?php 
    echo $this->session->flashdata('errorMessage');
    echo $this->session->flashdata('successMessage');
    echo form_open('category_con/add_category'); 
    echo form_fieldset('<h1 class="text-danger">Categories</h1>'); 
?>