Search code examples
phpmysqlcodeigniterinsert-update

How to insert on first time and update for the second time


I want to insert the row if it's a first entry of the day else I want to update the row..How can I do that..Currently I had done for update and don't know how to do it for insert..Please help me to achieve this..

This is my controller code:

$startdate = $this->input->post('TDate');
$date = str_replace('/', '-', $startdate);
$newDate = date("Y-m-d", strtotime($date));
$data1 = array(
        'tdate'=>$newDate,
        'total_credit'=>$total_credit['amount'],
        'total_debit'=>$total_debit['amount'],
       );
$this->db->where('tdate',$newDate);
$this->db->update('daytot',$data1);

Solution

  • Try below one

    $newDate   = date("Y-m-d", strtotime($this->input->post('TDate')));
    $data1     = array(
        'tdate'        => $newDate,
        'total_credit' => $total_credit['amount'],
        'total_debit'  => $total_debit['amount'],
    );
    
    //Check record is exist for the request date
    $objQuery = $this->db->get_where('daytot', array('tdate' => $newDate));
    if ($objQuery->num_rows() > 0) { //UPDATE
        $this->db->where('tdate', $newDate);
        $this->db->update('daytot', $data1);
    }
    else { //INSERT
        $this->db->insert('daytot', $data1);
    }
    

    Hope this will work :)