我的其他声明没有在它应该执行时执行。代码中没有错误。它只涉及我的查询和foreach语句的流程,但我似乎无法弄清楚这一点。有什么想法吗?
$id = $this->input->post('id');
$session_id = $this->input->post('session_id');
$q1 = $this->db->query("SELECT *
FROM default_cart
WHERE cookie_id = '$session_id'
AND product_id = '$id' LIMIT 1");
foreach($q1->result() as $row) {
if($row->cookie_id != $session_id && $row->product_id != $id) {
echo json_encode(array('error_code' => 'e100'));
} else {
$data = array('product_id' => $id,
'active' => 'Yes',
'cookie_id' => $session_id
);
$this->db->insert('default_cart', $data);
echo json_encode(array('success' => true));
}
}
答案 0 :(得分:3)
首先,我想建议当只有一条记录LIMIT 1
时没有循环查询的感觉,并且当你已经检查了所有参数时没有检查的感觉查询WHERE cookie_id = '$session_id' AND product_id = '$id'
只需获取查询返回的行并检查是否为空。
$id = $this->input->post('id');
$session_id = $this->input->post('session_id');
$q1 = $this->db->query("SELECT * FROM default_cart
WHERE cookie_id = '$session_id' AND product_id = '$id' LIMIT 1");
$row=$q1->row();
if(!empty($row)) {
$data = array('product_id' => $id,
'active' => 'Yes',
'cookie_id' => $session_id);
$this->db->insert('default_cart', $data);
echo json_encode(array('success' => true));
}else{
echo json_encode(array('error_code' => 'e100'));
}