duanlaiquan8174
2019-02-28 02:09
浏览 70
已采纳

使用codeigniter在数据库中插入多行

I want to insert multiple rows in the database with the use of codeigniter but i don't have any idea on how to properly implement it for my program to work. What I want is to fetch the data from the accounts table and use one of its attribute as a validation parameter in my if else statement. If the condition is met, it will populate the table with the announcement table contents along with the user id of all the accounts which met the proper conditions. Can you please help me to figure this thing out? Thank you.

Here's the snippet of my code.

CONTROLLER

public function announceSubmit(){
        $this->session->userdata('user_data');
        $id = $this->session->userdata('user_id');
        $uType = $this->session->userdata('user_type');
        $title = $this->input->post('title', true);
        $users = $this->input->post('users', true);
        $content = $this->input->post('descr', true);

        $config['upload_path'] = './uploads/announcements/';
        $config['allowed_types'] = 'jpg|png|jpeg';
        $config['max_size'] = '25000';

        $this->load->library('upload',$config);

            if(!$this->upload->do_upload('image-source')){
                print_r($this->upload->display_errors());
            }else{

                $newData = $this->Bid_Model->fetchItems('accounts');


                if($users == $uType){

                    foreach($newData as $user):
                        $userIDs = $user->user_id;
                    endforeach;

                        $announce_image = $this->upload->data('file_name');

                        $data = array(
                            'title' => $title,
                            'user_type' => $users,
                            'content' => $content,
                            'image' => $announce_image,
                            'admin_user_id' => $id,
                            'user_id' => $userIDs
                        ); 

                        $this->Bid_Model->insertItem('announcements', $data);
                }


                redirect('dashboard');
            }
        }

CREATE ANNOUNCEMENT VIEW

<style>
  #image-preview {
    display: none;
    width: 250px;
    height: 300px;
  }
  #cke_descr {
    margin-left:auto;
    margin-right:auto;
  }
</style>
<div class="right_col" role="main">
  <div class="">
    <div class="page-title">

      <div class="row">
        <div class="col-md-12 col-sm-12 col-xs-12">
          <div class="x_panel">
            <div class="x_title">
              <h2>Create Announcement</h2>
              <div class="clearfix"></div>
            </div>
            <div class="x_content">
              <br />
              <form id="demo-form2" data-parsley-validate class="form-horizontal form-label-left" method="post" enctype="multipart/form-data" action="<?=base_url()?>admin/announceSubmit">
                <div class="form-group">
                  <label class="control-label col-md-3 col-sm-3 col-xs-12" for="title">Title<span class="required">*</span>
                  </label>
                  <div class="col-md-6 col-sm-6 col-xs-12">
                    <input type="text" id="title" name="title" required="required" class="form-control col-md-7 col-xs-12">
                  </div>
                </div>
                <div class="form-group">
                  <label class="control-label col-md-3 col-sm-3 col-xs-12" for="users">Users <span class="required">*</span>
                  </label>
                  <div class="col-md-6 col-sm-6 col-xs-12">
                    <select type="text" id="users" name="users" required="required" class="form-control col-md-7 col-xs-12">
                      <option value="6">Vendor Team Manager</option>
                      <option value="2">Project Manager</option>
                      <option value="7">Vendor Project Manager</option>
                      <option value="3">Vice President</option>
                      <option value="5">Accountant</option>
                      <option value="8">Project Developers</option>
                    </select>
                  </div>
                </div>
                <div class="x_content">

                  <div class="class"></div>

                  <textarea required name="descr" id="descr" rows="10" cols="10"></textarea>

                  <div class="ln_solid"></div>

                  <div class="form-group">
                    <label class="control-label col-md-3 col-sm-3 col-xs-12">Upload an image <span class="required">*</span>
                    </label>
                    <div class="col-md-6 col-sm-6 col-xs-12">
                      <img id="image-preview" alt="image preview" />
                      <br />
                      <input type="file" name="image-source" id="image-source" onchange="previewImage();" required />
                    </div>
                  </div>
                  <div class="ln_solid"></div>
                  <div class="form-group">
                    <div class="col-md-6 col-sm-6 col-xs-12 col-md-offset-3">
                      <button class="btn btn-primary" type="reset">Reset</button>
                      <button type="submit" class="btn btn-success">Submit</button>
                    </div>
                  </div>
              </form>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</div>
</div>

DASHBOARD VIEW

<div class="clearfix"></div>
          <?php 
            if($announcements = $this->Bid_Model->fetchItems('announcements')):
            foreach ($announcements as $announce): 
              if($announce->user_type == 6){?>
            <div class="row">
              <div class="col-md-12 col-sm-12 col-xs-12">

              <div class="x_panel">
                <div class="x_title">
                  <h2>Announcement</h2>
                  <ul class="nav navbar-right panel_toolbox">
                    <li><a class="collapse-link"><i class="fa fa-chevron-up"></i></a>
                    </li>
                    <li class="dropdown">
                      <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-expanded="false"></a>
                    </li>
                    <li><a href="<?=base_url()?>Admin/deleteAnnouncement/<?=$announce->announcement_id?>" class="close-link"><i class="fa fa-close"></i></a>
                    </li>
                  </ul>
                  <div class="clearfix"></div>
                </div>

                <div class="x_content">
                <center>
                  <img src="<?php echo base_url().'uploads/';?>announcements/<?=$announce->image;?>" height="500" width="700">

                  <h4><?=$announce->title?></h4>
                  <h4><?=$announce->content?></h4>
                </center>

                <div class="ln_solid"></div>
                  <!-- modals -->

                </div>
              </div>
            </div>
            </div>
             <?php } endforeach; endif; ?>
                  <!-- /modals -->
          <br />

MODEL

<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Bid_Model extends CI_Model {

    function fetchItems($table, $data = NULL){
        if ($data != NULL){
            $this->db->where($data);
        }

        $query = $this->db->get($table);
        return ($query->num_rows() > 0) ? $query->result() : FALSE;
    }

    function deleteItem($table,$array=NULL){
        if($array!=NULL){
            $this->db->where($array);
             $this->db->delete($table);
        }else{
            $this->db->empty_table($table); 
        } 
    }

    function insertItem($table, $data = NULL){
        $this->db->insert($table, $data);
    }

    function insertItems($table,$data = array()){
        $this->db->insert_batch($table, $data);
    }


    function updateItem($table, $data, $var = NULL){
        if($var != NULL){
            $this->db->where($var);
        }
        $this->db->update($table, $data);
    }


}
  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • douyi7055 2019-02-28 07:55
    已采纳

    Since you've said you want to insert multiple rows, I assume that you want to do a batch-insert using data previously selected from fetchItems() function. You could try it like this :

            $newData = $this->Bid_Model->fetchItems('accounts');
    
            if($users == $uType){
    
                $announce_image = $this->upload->data('file_name');
                $data = []; // new empty array
                foreach($newData as $user):
                    $userIDs = $user->user_id;
    
                    $data[] = array(
                        'title' => $title,
                        'user_type' => $users,
                        'content' => $content,
                        'image' => $announce_image,
                        'admin_user_id' => $id,
                        'user_id' => $userIDs
                    ); 
                endforeach;
    
                $this->Bid_Model->insertItems('announcements', $data);
            }
    
    点赞 打赏 评论
  • doufen1890 2019-02-28 03:50

    Assuming that data passed to insertItems is all cleaned and you want to insert it directly to DB without any changes.

    DB function:

    function insert_batch($data) {
       $query = 'INSERT INTO TABLE (`title`, `user_type`, `content`, `image`, 
                                    `admin_user_id`, `user_id`) VALUES ';
       $insert_data = [];
       for($x=0; $x<count($data); $x++){
        $insert_data[] = "('" . $data['title'] . "', '" . $data['user_type'] . "', '" . $data['content'] . "', '" . $data['image'] . "', '" . $data['admin_user_id'] . "','" . $column2['user_id'] . "')";
        }
        $query .= implode(',', $insert_data); //Execute this $query
    }
    
    点赞 打赏 评论

相关推荐 更多相似问题