我的计算有点问题,当我传递折扣和借记值时,它正在执行其工作,但当折扣和借记的值为空时,它返回空白页面。这是我的模特.. 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;
}
答案 0 :(得分:3)
最好的方法是使用三元运算符。
$subtotal = $this->input->post('subTotal') == "" ? 0 : $this->input->post('subTotal');
如果您的php版本是7.0>,请使用
$subtotal = $this->input->post('subTotal') ?? 0;
答案 1 :(得分:1)
在分配借方和折扣的价值时,在数据数组中使用三元运算符。代码如下所示:
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') - isset($this->input->post('discount'))?$this->input->post('discount'):0,
'Discount' => isset($this->input->post('discount'))?$this->input->post('discount'):0',
'Debit' => isset($this->input->post('debit'))?$this->input->post('debit'):0,
'Payment_Cridet' => $this->input->post('total') - isset($this->input->post('debit'))?$this->input->post('debit'):0 - isset($this->input->post('discount'))?$this->input->post('discount'):0',
'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;
}
答案 2 :(得分:1)
三元运算符逻辑是使用(condition) ? (true return value) : (false return value)
语句来缩短if/else
结构的过程。
因此,如果输入文本为空,则可以使用三元运算符登录来传递零。
现在,像我这样的createInvoice()
功能发生了一些变化:
$subTotal = $this->input->post('subTotal') == "" ? 0 : $this->input->post('subTotal');
$total = $this->input->post('total') == "" ? 0 : $this->input->post('total');
$discount = $this->input->post('discount') == "" ? 0 : $this->input->post('discount');
$debit = $this->input->post('debit') == "" ? 0 : $this->input->post('debit');
$data = array(
'Date' => $date,
'Terms_Of_Payment' => $this->input->post('termsOfPayment'),
'Sub_Total' => $subTotal,
'Total' => ($total - $discount),
'Discount' => $discount,
'Debit' => $debit,
'Payment_Cridet' => $total - $debit - $discount,
'Note' => $this->input->post('note'),
'Customer_ID' => $this->input->post('customerId'),
'User_ID' => $this->session->userdata('id')
);