在codeIgniter中获取最新的更新记录ID?

时间:2017-03-07 04:56:56

标签: php mysql codeigniter

我来到这里另一个问题我已经工作了大约5个小时但没有运气。 我有一个像下面的图像表。 My Images table

我已成功将数据插入其中。

现在我想通过使用下面的视图,控制器和Model类来更新插入的数据。 我的观看课程

 <form role="form" method="post" enctype="multipart/form-data" action="<?php echo base_url('admin/updateCategory'); ?>">
          <div class="box-body">
            <div class="form-group">
     <input type="hidden" value='<?php echo $catDataForEdit->cat_id; ?>' name="id_hidden">
              <label for="exampleInputEmail1">Category Name</label>
              <input type="text" class="form-control" id="exampleInputEmail1" name="category_name" placeholder="Category Name" value='<?php echo $catDataForEdit->category_name; ?>' >
            </div>

            <div class="form-group">
              <label for="exampleInputEmail1">Upload Category Icon</label>
              <!--input type="text" class="form-control" id="exampleInputEmail1" placeholder="Category Icon"-->
              <p class="grey-color mt-0">Icon Size: Width: 26px, Height: 28px and Icon Format: .png</p>
              <input type="file" name="cat_icon" value='<?php echo $catDataForEdit->iconName; ?>'>
            </div>
            <div class="form-group">
               <label for="exampleInputEmail1">Upload Category Image</label>
              <p class="grey-color mt-0">Image Size: Width: 175px, Height: 120px and Image Format: .png</p>
              <input type="file" name="cat_image" value='<?php echo $catDataForEdit->imageName; ?>'>
            </div>
          </div>
          <!-- /.box-body -->

          <div class="box-footer box-footer-border">
            <div class="row">
                <div class="col-lg-6 col-md-6 col-sm-12 col-xs-12">
                    <input type="submit" class="btn btn-primary" name="update_cat_submit" value="Modify">
                </div>
            </div>

我的Controller Admin.php:

 public function updateCategory(){
    $data = array();
    $targetDir = "images/dynamic/";
    $prevcatIconName; $prevCatImageName;
    $catIconName; $category_name; $catImageName; 
    $targetFilePathIcon; $targetFilePathImage; 
    $date; $unix_time;$hidden_id;
    $hidden_id = $this->input->post('id_hidden');
    if ($this->input->post('update_cat_submit')) {

        $this->form_validation->set_rules('category_name', 'Category Name', 'trim|required');
      if ($this->form_validation->run() == false) {
        $this->modifyCategory($hidden_id);
      }else{

          $category_name = $this->input->post('category_name');


    //Category Icon
    if ( !empty($_FILES["cat_icon"]["name"])) {
      //getting values from view
         $catIconName = basename($_FILES["cat_icon"]["name"]);
         $targetFilePathIcon = $targetDir . $catIconName;
         $iconFileType = pathinfo($targetFilePathIcon,PATHINFO_EXTENSION);


      //allow certain file formats
      $allowTypes = array('jpg','png','jpeg','gif');
      if(in_array($iconFileType, $allowTypes)){
          //upload file to server
          if(move_uploaded_file($_FILES["cat_icon"]["tmp_name"], $targetFilePathIcon)){
             // echo "The file ".$fileName. " has been uploaded.";


              //Category Image
            if ( !empty($_FILES["cat_image"]["name"])) {
               $catImageName = basename($_FILES["cat_image"]["name"]);
               $targetFilePathImage = $targetDir . $catImageName;
               $imageFileType = pathinfo($targetFilePathImage,PATHINFO_EXTENSION); 
               // echo $catIconName . ','. $catImageName;
                //allow certain file formats
              $allowTypes = array('jpg','png','jpeg','gif');
              if(in_array($imageFileType, $allowTypes)){
                  //upload file to server
                  if(move_uploaded_file($_FILES["cat_image"]["tmp_name"], $targetFilePathImage)){
                 // echo "The file ".$fileName. " has been uploaded.";
                     $date = date('Y-m-d H:i:s');
                     $unix_time=human_to_unix($date);

                //insert Category Icon into db and get CatIconId
                    $fields = array(
                  'image_name' => $catIconName,
                  'modified_at' => $unix_time,
                  'status'     => 'a'

                  );
                    //print_r($fields);
                 $iconId = $this->img_model->updateImages($fields); 
                  //echo $iconId;

                //insert Category Image
                    $fields = array(
                  'image_name' => $catImageName,
                  'modified_at' => $unix_time,
                  'status'     => 'a'

                  );

              $imageId = $this->img_model->updateImages($fields);
              //echo $iconId . ',' .$imageId;
                echo $imageId;
                //echo $unix_time;
                if ($imageId != "" && $iconId != "" ) {
                  $next_fields = array(

                    'cat_name' => $category_name,
                    'cat_icon' => $iconId,
                    'cat_image' =>$imageId,
                    'modified_at'=>$unix_time,
                    'status' =>'a'

                    );
                 // print_r($next_fields); die();
                  $result = $this->cat_model->updateCatNames($hidden_id,$next_fields);
                if ($result) {
                    //$this->Category();
                    redirect(base_url('admin/Category'));
                    //$this->load->view('admin/category');

                }else{
                  $data['error_msg'] = 'there is problem with your input';
                }

            }


              }else{


                  $data['error_msg'] = 'Sorry, there was an error uploading your image.';
                 $this->modifyCategory($hidden_id);
              }//move_uploaded_file if else loop close
          }else{

              $data['error_msg'] = 'Sorry, only JPG, JPEG, PNG, GIF images are allowed to upload.';
              $this->modifyCategory($hidden_id);
          }//in_array if else loop close
              }else{

                $data['error_msg'] = 'Please select a image to upload.';
               $this->modifyCategory($hidden_id);
              }//empty file verification close

          }else{

             $data['error_msg'] = 'Sorry, there was an error uploading your Icon.';
             $this->modifyCategory($hidden_id);
          }//move_uploaded_file if else loop close
      }else{

          $data['error_msg'] = 'Sorry, only JPG, JPEG, PNG, GIF icons are allowed to upload.';
          $this->modifyCategory($hidden_id);
      }//in_array if else loop close
  }else{

      $data['error_msg'] = 'Please select a icon to upload.';
      $this->load->view('admin/modify-category', $data);
    }
  }
}


} 

我的模型类Img_model:

 public function updateImages($fields){
    $id = $this->input->post('id_hidden');

    $this->db->where('id', $id);
    $query = $this->db->update('images', $fields);

   if($this->db->affected_rows() > 0){

      $this->db->where($fields);
     $result = $this->db->get('images')->row()->id;
     //echo $result;
     return $result;

     //I have tried like below to get the last insert id but unable to get.
     //return $this->db->insert_id();
   }else{

    return false;
   }   
}//close update Images

我的模型Cat_model:

 public function updateCatNames($hidden_id,$next_fields){
 $this->db->where('id', $hidden_id);
  $this->db->update('categories', $next_fields);
  if($this->db->affected_rows() > 0){
    return true;
  }else{
    return false;
  } 
  }

我试图从我的Img_model类中获取最新的插入记录ID,但无法获取它。有人可以帮帮忙吗? 提前谢谢!

3 个答案:

答案 0 :(得分:0)

试试这个:

if( $this->db->update('categories', $next_fields) )
{
    echo $hidden_id;
}

$this->db->update()TRUE / FALSE执行查询时返回successful / failed。所以上面的代码只有在查询成功执行时才会echo $hidden_id

答案 1 :(得分:0)

首先Try this

其次,您的表格图片中没有cat_id字段。如何在图像和类别表之间创建关系。请参阅下面的示例图片

enter image description here

我有一个property_images表,我有这样的property_id我也可以拥有该属性的多个图像。但是,由于只有一个类别图像,因此在图像表中放置category_id会使查询结构更加简单。

您只需更新包含您要发送的类别ID的记录,并返回完整记录,以防您想从中获取记录的ID。

您的案例

     $fields = array(
     'image_name' => $catImageName,
     'modified_at' => $unix_time,
     'status'     => 'a'
     );
     $imageId = $this->img_model->updateImages($fields);

您正在使用上面的代码来更新您从视图中发送类别ID的图像表

<input type="hidden" value='<?php echo $catDataForEdit->cat_id; ?>' name="id_hidden">

并且在您的图片模型中,您将获得该类别ID以更新图片记录

$id = $this->input->post('id_hidden');

$this->db->where('id', $id);
$query = $this->db->update('images', $fields);

现在你想获得你更新的图像ID,你可以通过这段代码得到它

 $st=$this->db->select('*')->from('images')->WHERE('image_name',$fields['image_name'])->get()->result_array();
 $updatedRecordId=$st[0]['id']
 // Now you can return it or use it. 

但这对我没有任何意义。

答案 2 :(得分:0)

在您的模型类Img_model上:

public function updateImages($fields){
    $id = $this->input->post('id_hidden');

    $this->db->where('id', $id);
    $query = $this->db->update('images', $fields);

   if($this->db->affected_rows() > 0){
        return $id;
        // $id is your updated record id because it is unique.
   }else{
    return false;
   }   
}