Search code examples
codeignitercodeigniter-2codeigniter-3

How to pass zero if input text is blank?


I am getting a bit issue with my calculation, when I pass Discount and Debit values it is doing its job, but when Values of Discount and Debit is nothing it returns a blank page. Here is my Model.. CODEIGNITER.

function createInvoice() {
    $this->load->helper('date');
    $date = date('Y-m-d H:i:s');
    $data = array(
        'Date'              => $date,
        'Terms_Of_Payment'  => $this->input->post('termsOfPayment'),
        'Sub_Total'         => $this->input->post('subTotal'),
        'Total'             => $this->input->post('total') - $this->input->post('discount'),
        'Discount'          => $this->input->post('discount'),
        'Debit'             => $this->input->post('debit'),
        'Payment_Cridet'    => $this->input->post('total') - $this->input->post('debit') - $this->input->post('discount'),
        'Note'              => $this->input->post('note'),
        'Customer_ID'       => $this->input->post('customerId'),
        'User_ID'           => $this->session->userdata('id'));

    $this->db->insert('invoice', $data);
    return ($this->db->affected_rows() != 1) ? false : true;
}

Solution

  • The best way is to use the ternary operator.

    $subtotal = $this->input->post('subTotal') == "" ? 0 : $this->input->post('subTotal');
    

    And if your php version is 7.0> then use

    $subtotal = $this->input->post('subTotal') ?? 0;