Michael Grigsby
Michael Grigsby

Reputation: 12163

PHP else statement not executing

My else statement is not getting executed when it should. There are no errors in the code. It simply has to do with the flow of my query and foreach statement but I cannot seem to figure this out. Any ideas?

$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));
    }
}

Upvotes: 0

Views: 100

Answers (1)

M Khalid Junaid
M Khalid Junaid

Reputation: 64476

First, I would like to suggest that there is no sense of looping through the query when there is only one record LIMIT 1 and no sense of if check while you have already checked the all parameters in the query WHERE cookie_id = '$session_id' AND product_id = '$id' just fetch the row returned by the query and check for empty or not.

    $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'));
    }

Upvotes: 3

Related Questions