简体   繁体   English

如何第一次插入表格数据,第二次更新相同数据?

[英]how to insert form data first time and second time update same data?

code: 码:

<?php
    if($this->input->post('submit'))
    {
        $data = array(
                'enq_id'=> $this->input->post('ids'),
                'status' => $this->input->post('status'),
                'follow_up_date' => date('d-m-Y')
                );
        $query = $this->db->insert('enq_process',$data);
        if($query == true)
        {
            echo "<p style='color:green;font-size:12px;text-align:center;'>Your data successfully save.</p>";
        }
        else
        {
            echo "<p style='color:red;font-size:12px;text-align:center;'>Error!</p>";
        }
    }
?>

I have a form having input field name (ids,status) with submit button. 我有一个带有输入字段名称(ID,状态)和提交按钮的表单。 Now, I am inserting form data into database now I want that when from data inserting first time then how to update same form data second time ? 现在,我要将表单数据插入数据库,现在我希望从第一次插入数据到第二次如何更新相同的表单数据?

$ this-> db-> insert_id()将返回最后插入的行ID,因此您可以在下一个查询中使用此ID。

Hi you can use the following way : First check whether the data by its condition is present in your database table. 嗨,您可以使用以下方式:首先检查数据库表中是否存在按其条件显示的数据。 If exists then update else insert your data 如果存在,则更新,否则插入您的数据

if(post request){
    Step 1 : Check whether enqid along with some condtion is already present or not in database table

    Step 2: 
        if (exists) {
            UPDATE
        } else { 
            INSERT
        }

}

try this 尝试这个

$q = $this->db->get('enq_process');

   if ( $q->num_rows() > 0 ) 
   {
      $this->db->where('ids',$data['enq_id']);
      $this->db->update('enq_process',$data);
   } else {

      $this->db->insert('enq_process',$data);
   }

make new function in same controller 在同一控制器中创建新功能

public function insert_or_update($table='', $data=array()){
    $seprator=" ";
    $update="";
  foreach ($data as $feild => $value) {
    $update.=$seprator."`$feild`='$value'";
    $seprator=', ';
  }
  $sql = $this->db->insert_string('table', $data) . ' ON DUPLICATE KEY UPDATE '.$update;
  if($this->db->query($sql)){
    return $this->db->insert_id();
  }else{
    return false;
  }
}

and use this function in your controller 并在控制器中使用此功能

 if($this->input->post('submit'))
    {
        $data = array(
                'enq_id'=> $this->input->post('ids'),
                'status' => $this->input->post('status'),
                'follow_up_date' => date('d-m-Y')
                );
        $query = $this->insert_or_update('enq_process',$data);
        if($query == true)
        {
            echo "<p style='color:green;font-size:12px;text-align:center;'>Your data successfully save.</p>";
        }
        else
        {
            echo "<p style='color:red;font-size:12px;text-align:center;'>Error!</p>";
        }
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM