01/10/2018, 10:55

Chèn dữ liệu từ 1 form vào hai bảng khác nhau trong codeigniter

mình có 2 bảng như sau:
bảng attribute

atribute_id
attribute_images
attribute_color_id
product_id
attribute_order

Bảng
product có các trường sau

product_id
product_name
product_price
product_images

Giờ mình muốn chèn 1 sản phẩm, có các màu sắc khác nhau như xanh thì có ảnh màu xanh màu đỏ thì ảnh màu đỏ nhưng chỉ trong 1 form.
sản phẩm mình đã chèn được, ảnh cũng đã upload lên, nhưng giá trị khi thêm vào thì không chèn vào database
code của mình thế này
file controller

    public function add_new_car(){
            if($this->is_admin() == TRUE){
                $this->loadThis();
            }
            else{
                $this->load->library('form_validation');
                $this->load->library("upload");
                $this->form_validation->set_rules('title', 'Tiêu đề', 'required');
                $this->form_validation->set_rules('slug', 'Đường dẫn', 'trim|required');
                $config['upload_path'] = './upload/cars/';
                $config['allowed_types'] = 'gif|jpg|png|jpeg';
                $this->upload->initialize($config); 
                $this->upload->do_upload('post_images');
                $image_data = $this->upload->data();
                $post_images = $image_data['file_name'];
                //bien chua cac ten file upload
                $name_array = array();
                 
                //lưu biến môi trường khi thực hiện upload
                $file  = $_FILES['anh'];
                $count = count($file['name']);
                $img = ';
                for($i=0; $i<=$count-1; $i++) 
                {
                      
                    $_FILES['userfile']['name']     = $file['name'][$i];  //khai báo tên của file thứ i
                    $_FILES['userfile']['type']     = $file['type'][$i]; //khai báo kiểu của file thứ i
                    $_FILES['userfile']['tmp_name'] = $file['tmp_name'][$i]; //khai báo đường dẫn tạm của file thứ i
                    $_FILES['userfile']['error']    = $file['error'][$i]; //khai báo lỗi của file thứ i
                    $_FILES['userfile']['size']     = $file['size'][$i]; //khai báo kích cỡ của file thứ i
                      //load thư viện upload và cấu hình
                    $this->load->library('upload', $config);
                      //thực hiện upload từng file
                    if($this->upload->do_upload())
                    {
                          //nếu upload thành công thì lưu toàn bộ dữ liệu
                        $data = $this->upload->data();
                          //in cấu trúc dữ liệu của các file
                        $img .= $data['file_name'].'#';
                    }     
                }
                $img = rtrim($img, '#');
                if($this->form_validation->run() == false){
                    $this->addnew();
                }
                else{
                    $title = $this->input->post('title');
                    $slug = $this->input->post('slug');
                    $pdescription = $this->input->post('pdescription');
                    $price = $this->input->post('price');
                    $pcontent = $this->input->post('pcontent');
                    $cat_id = $this->input->post('cat_id');
                    $status = $this->input->post('status');
                    $km = $this->input->post('mkm');
                    $car_info = array(
                        'car_name' => $title,
                        'car_slug' => $slug,
                        'car_description' => $pdescription,
                        'car_images' => $post_images,
                        'car_price' => $price,
                        'car_cat_id' =>$cat_id,
                        //'car_gallery' =>$gallery,
                        'car_km' =>$km,
                        'car_content' =>$pcontent,
                        'car_status'=>$status,
                        'is_delete' =>0,
                        'post_by' =>$this->vendorid,
                        'post_create'=>date('Y-m-d H:i:s')
                        );
                    $result = $this->car_model->add_new_car($car_info);
                    if($result > 0)
                    {
                        $this->session->set_flashdata('success', 'Thêm bài viết mới thành công');
                    }
                    else
                    {
                        $this->session->set_flashdata('error', 'Thất bại');
                    }
                    
                    redirect('admin/car');
                }
            }
        }

file model

public function add_new_car($postInfo){
            $this -> db -> insert('car',$postInfo);
            /*
            ** Kiem tra xem viec insert vao db co thanh cong hay khong
            */
            if ($this -> db -> affected_rows() > 0) {
                /*
                ** Lay ra id cua product vua insert thanh cong vao db,
                ** de xac dinh viec insert cho cac anh? thuoc product nay
                */
                $prdid = $this -> db -> insert_id();
                /*
                ** Khi insert thanh cong product thi kiem tra xem co anh duoc nguoi dung them vao khong
                ** Neu co thi tiep tuc insert vao database cac anh duoc them cho product boi nguoi dung
                **
                ** @param : + imgarray : Chua tat ca cac anh ma nguoi dung quyet dinh them vao product.
                */
                $imgarray = $this -> input -> post("anh");
                $mau = $this -> input -> post("mau");
                if ($imgarray != false) {
                    /*
                    ** Load image model de thuc hien insert anh vao db
                    ** model co path nhu sau : ../modules/administrator/models/images_product_model.php
                    */
                    /*
                    ** Neu co anh nguoi dung them vao, thi insert vao db bang cach dung vong lap for ben duoi
                    */
                    for($i=0; $i < count($imgarray); $i++){
                        /*
                        ** Thuc hien insert vao db
                        ** @param : + $imgarray[$i] : url cua anh muon insert vao db
                        **          + $prdid : Chcinh id cua product muon insert anh? cho no
                        **          + $orderarray[$i] : la thu tu hien thi cua tung anh. co the rong~ cung~ duoc.
                        */
                        if (is_array($imgarray[$i])) {
                            $this -> Prd_image_insert_single($anh[$i]['value'],$mau[$i]['value'],$prdid);
                        } else {
                            $this ->Prd_image_insert_single($imgarray[$i],$mau[$i],$prdid);
                        }
                    }
                }
                return $prdid;
            }
            return false;
        }

file view

<div class="content-wrapper">
    <!-- Content Header (Page header) -->
    <section class="content-header">
      <h1>
        <i class="fa fa-users"></i> Quản lý Bài viết
        <small>Add / Edit User</small>
      </h1>
    </section>
    <script language="javascript">
            function ChangeToSlug()
            {
                var title, slug;
 
                //Lấy text từ thẻ input title
                title = document.getElementById("title").value;
 
                //Đổi chữ hoa thành chữ thường
                slug = title.toLowerCase();
 
                //Đổi ký tự có dấu thành không dấu
                slug = slug.replace(/á|à|ả|ạ|ã|ă|ắ|ằ|ẳ|ẵ|ặ|â|ấ|ầ|ẩ|ẫ|ậ/gi, 'a');
                slug = slug.replace(/é|è|ẻ|ẽ|ẹ|ê|ế|ề|ể|ễ|ệ/gi, 'e');
                slug = slug.replace(/i|í|ì|ỉ|ĩ|ị/gi, 'i');
                slug = slug.replace(/ó|ò|ỏ|õ|ọ|ô|ố|ồ|ổ|ỗ|ộ|ơ|ớ|ờ|ở|ỡ|ợ/gi, 'o');
                slug = slug.replace(/ú|ù|ủ|ũ|ụ|ư|ứ|ừ|ử|ữ|ự/gi, 'u');
                slug = slug.replace(/ý|ỳ|ỷ|ỹ|ỵ/gi, 'y');
                slug = slug.replace(/đ/gi, 'd');
                //Xóa các ký tự đặt biệt
                slug = slug.replace(/`|~|!|@|#|||$|\%|^|&|*|(|)|+|=|,|.|/|?|>|<|'|"|:|;|_/gi, ');
                //Đổi khoảng trắng thành ký tự gạch ngang
                slug = slug.replace(/ /gi, "-");
                //Đổi nhiều ký tự gạch ngang liên tiếp thành 1 ký tự gạch ngang
                //Phòng trường hợp người nhập vào quá nhiều ký tự trắng
                slug = slug.replace(/-----/gi, '-');
                slug = slug.replace(/----/gi, '-');
                slug = slug.replace(/---/gi, '-');
                slug = slug.replace(/--/gi, '-');
                //Xóa các ký tự gạch ngang ở đầu và cuối
                slug = '@' + slug + '@';
                slug = slug.replace(/@-|-@|@/gi, ');
                //In slug ra textbox có id “slug”
                document.getElementById('slug').value = slug;
            }
        </script>
    <section class="content">
    
        <div class="row">
			<div class="col-md-12">
				 <?php
                    $this->load->helper('form');
                    $error = $this->session->flashdata('error');
                    if($error)
                    {
                ?>
                <div class="alert alert-danger alert-dismissable">
                    <button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
                    <?php echo $this->session->flashdata('error'); ?>  
				</div>
				<?php } ?>
                <?php  
                    $success = $this->session->flashdata('success');
                    if($success)
                    {
                ?>
                <div class="alert alert-success alert-dismissable">
                    <button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
                    <?php echo $this->session->flashdata('success'); ?>
                </div>
                <?php } ?>
				<div class="row">
                    <div class="col-md-12">
                        <?php echo validation_errors('<div class="alert alert-danger alert-dismissable">', ' <button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button></div>'); ?>
                    </div>
                </div>
            <!-- left column -->
			<form role="form" id="add_post" action="<?php echo base_url() ?>admin/car/add_new_car" method="post" role="form" enctype="multipart/form-data">
            <div class="col-md-9">
              <!-- general form elements -->
                <div class="box box-primary">
                    <div class="box-header">
                        <h3 class="box-title">Thêm bài viết mới</h3>
                    </div><!-- /.box-header -->
                    <!-- form start -->
                    
                   
                        <div class="box-body">
                            <div class="row">
                                <div class="col-md-12">
                                    <div class="nav-tabs-custom">
                                        <ul class="nav nav-tabs">
                                          <li class="active"><a href="#tab_1" data-toggle="tab">Chung</a></li>
                                          <li><a href="#tab_2" data-toggle="tab">Hình ảnh</a></li>
                                          <li><a href="#tab_3" data-toggle="tab">Khuyến mãi</a></li>
                                          <li><a href="#tab_4" data-toggle="tab">Hình ảnh thực tế</a></li>
                                          <li><a href="#tab_5" data-toggle="tab">Giới thiệu</a></li>
                                          <li class="pull-right"><a href="#" class="text-muted"><i class="fa fa-gear"></i></a></li>
                                        </ul>
                                        <div class="tab-content">
                                          <div class="tab-pane active" id="tab_1">
                                            <div class="form-group">
                                                <label for="title">Tiêu đề</label>
                                                <input type="text" class="form-control required" id="title" name="title" onkeyup="ChangeToSlug();">
                                            </div>
                                            <div class="form-group">
                                                <label for="slug">Đường dẫn</label>
                                                <input type="text" class="form-control required slug" id="slug"  name="slug">
                                            </div>
                                            <div class="form-group">
                                                <label for="slug">Giá</label>
                                                <input type="text" class="form-control" id="price"  name="price">
                                            </div>
                                            <div class="form-group">
                                                <label for="password">Mô tả</label>
                                                <textarea class="form-control required" name="pdescription"></textarea>
                                            </div>

                                          </div>
                                          <!-- /.tab-pane -->
                                          <div class="tab-pane" id="tab_2">
                                            <div id="dynamicInput">
                                                <div class="row">
                                                    <div class="col-md-6">
                                                        <div class="form-group">
                                                            <label for='Gallery'>Màu sắc</label>
                                                            <select class="form-control" name="mau">
                                                                <?php if(!empty($colors)){
                                                                    foreach ($colors as $color){ ?>
                                                                <option value='<?php echo $color->color_id;?>'><?php echo $color->color_name;?></option>
                                                                <?php } } ?>
                                                            </select>
                                                        </div>
                                                    </div>
                                                    <div class="col-md-6">
                                                        <div class="form-group">
                                                            <label for='Gallery'>Hình ảnh</label>
                                                            <input type = 'file' name="anh" />
                                                        </div>
                                                    </div>
                                                </div>
                                            </div>
                                            <!--<input type="button" value="Add another text input" onClick="addInput('dynamicInput');">-->
                                        </div>
                                        <!-- /.tab-pane -->
                                        <div class="tab-pane" id="tab_3">
                                            <div class="form-group">
                                                <label for="cpassword">Nội dung</label>
                                                <textarea class="form-control required" id="pcontent" name ="mkm"></textarea>
                                            </div>
                                        </div>
                                        <!-- /.tab-pane -->
                                        <div class="tab-pane" id="tab_4">
                                            <div class="form-group">
                                                <label for="cpassword">Hình ảnh thực tế</label>
                                                <textarea class="form-control required" id="pcontents" name ="gallery"></textarea>
                                            </div>
                                        </div>
                                        <!-- /.tab-pane -->
                                        <div class="tab-pane" id="tab_5">
                                            <div class="form-group">
                                                <label for="cpassword">Giới thiệu</label>
                                                <textarea class="form-control required" id="pcontent2" name ="pcontent"></textarea>
                                            </div>
                                        </div>
                                        <!-- /.tab-pane -->
                                        </div>
                                    <!-- /.tab-content -->
                                    </div>
                                <!-- nav-tabs-custom -->
                                                              
                                </div>
                            </div>
                            
                        </div><!-- /.box-body -->
    
                    
                </div>
            </div>
            <div class="col-md-3">
				<div class="box box-primary">
                    <div class="box-header">
                        <h3 class="box-title">Danh mục</h3>
                    </div><!-- /.box-header -->
					 <div class="box-body">
						<div class="form-group">
							<select multiple="" class="form-control" name="cat_id">
								<?php if(!empty($brands)){
									foreach($brands as $cat){
								?>
								<option value="<?php echo $cat->cat_id;?>"><?php echo $cat->cat_name; ?></option>
								<?php } } ?>
							</select>
						</div>
					 </div>
				</div>
				<div class="box box-primary">
                    <div class="box-header">
                        <h3 class="box-title">Trạng thái bài viết</h3>
                    </div><!-- /.box-header -->
					 <div class="box-body">
						<?php if(!empty($poststatus)){
							foreach ($poststatus as $status){
								?>
								<div class="checkbox">
							  <label>
								<input type="radio" name="status" value="<?php echo $status->status_id ?>"> <?php echo $status->status_name ?>
							  </label>
							</div>
						<?php 		
							}
						} ?> 
					 </div>
				</div>
				<div class="box box-primary">
                    <div class="box-header">
                        <h3 class="box-title">Hình ảnh</h3>
                    </div><!-- /.box-header -->
					 <div class="box-body">
						<div class="form-group">
						   <input type="file" name="post_images" id="userfile" size="20" />
						</div>
					 </div>
				</div>
				<div class="box box-primary">
                    <div class="box-header">
                        <h3 class="box-title">Đăng bài</h3>
                    </div><!-- /.box-header -->
					 <div class="box-body">
						<div class="form-group">
							<input type="submit" class="btn btn-primary" value="Đăng" />
                            <input type="reset" class="btn btn-default" value="Nhập lại" />
						</div>
					 </div>
				</div>
             </div>
			</form>		
                
                
            </div>
        </div>    
    </section>
    
</div>

<script src="https://cdn.ckeditor.com/4.5.7/standard/ckeditor.js"></script>
<script>
  $(function () {
    // Replace the <textarea id="editor1"> with a CKEditor
    // instance, using default configuration.
    CKEDITOR.replace('pcontent');
    CKEDITOR.replace('pcontents');
    CKEDITOR.replace('pcontent2');
    //bootstrap WYSIHTML5 - text editor
  });


  var counter = 2;
  function addInput(divName){

      var newdiv = document.createElement('div');
      newdiv.innerHTML ="<div class='row'><div class='col-md-6'><div class='form-group'><label for='Gallery'>Màu sắc</label><select class='form-control' name='mau[]'><?php if(!empty($colors)){foreach ($colors as $color){ ?><option value='<?php echo $color->color_id;?>'><?php echo $color->color_name;?></option><?php } } ?></select></div></div><div class='col-md-6'><div class='form-group'><label for='Gallery'>Hình ảnh</label><input type = 'file' name='anh[]' /></div></div></div>";
      document.getElementById(divName).appendChild(newdiv);
      counter++;
    }
</script>

Liệu mình có sai ở đâu không ạ? mọi người xem giúp mình với, đau đầu mất 3 ngày mà chưa giải quyết được

Thuc Nguyen Tan viết 12:55 ngày 01/10/2018

Sao bạn không lưu ảnh ngoài file, hình như dễ hơn lưu vào database?

Hoàng Minh Hướng viết 13:08 ngày 01/10/2018

Sao bạn không lưu ảnh ngoài file, hình như dễ hơn lưu vào database?

ảnh đã lưu lên trên server, còn vấn đề của mình là bảng atribute của mình không lưu được thôi

Thuc Nguyen Tan viết 12:56 ngày 01/10/2018

Product=(product_id
product_name
product_price
product_images)

Theo bảng này thì 1 cái product id của bạn chỉ lưu 1 hình, vậy khi nhập lên có rất nhiều hình vậy bạn lưu cái nào
rec={ 001,‘Quat may’,2000,‘abcde.jpg’ }

Hoàng Minh Hướng viết 13:08 ngày 01/10/2018

Product=(product_id
product_name
product_price
product_images)

Theo bảng này thì 1 cái product id của bạn chỉ lưu 1 hình, vậy khi nhập lên có rất nhiều hình vậy bạn lưu cái nào
rec={ 001,‘Quat may’,2000,‘abcde.jpg’ }

mình lưu vào cái bảng atribute đó bạn, giờ mình đã giải quyết xong vấn đề đó rồi, còn 1 vấn đề nữa là không biết là nếu thêm vào đó 1 cột nữa thì lưu riêng 1 cột dưới dạng json được không nhỉ, hay là phải lưu cả table dưới dạng json

Thuc Nguyen Tan viết 13:04 ngày 01/10/2018

Thêm vào cũng được thôi, có thể dạng json :{‘a.jpg’,‘b.jpg’,‘c.jpg’} nhưng cũng nên cân nhắc có cần không vì sẽ làm phức tạp vì khi thêm xóa sửa bảng addtribute bạn phải chạy vào cập nhật lại cột này.

Bài liên quan
0