Michael Grigsby
Michael Grigsby

Reputation: 12173

Codeigniter not properly processing a foreach loop

I've got about 10 rows in my db and 3 of which have status == to 'Pass'. The problem I've noticed with the code below is with the foreach loop. It's not wanting to work properly. I can't even get the script to send the jSON data back to the browser which means the script isn't processing past the foreach statement. Does anybody know how to fix this?

public function logsig() {
        header('Content-type:application/json');
        $postedUser = $this->input->post('username');
        $password = $this->input->post('password');
        $hashedPass = $this->encrypt->sha1($password);
        $query = $this->db->query("SELECT * FROM users WHERE username = '{$postedUser}' AND password = '{$hashedPass}'");
        foreach ($query->result() as $row) {
            if ($row->status == "Pass") {
                if ($query->num_rows() > 0) {
                    $this->session->set_userdata('logged', "1");
                    $this->session->set_userdata("username", "{$postedUser}");
                    echo json_encode(array('session_state' => true));
                } else {
                    echo json_encode(array('session_state' => false));
                }
            } elseif ($row->status == "Fail" || "Pending") {
                exit;
            }
        }
    }

Upvotes: 0

Views: 179

Answers (2)

gen_Eric
gen_Eric

Reputation: 227310

You're echoing the JSON in each iteration of the loop. This will make something like this:

{"session_state": true}{"session_state": false}

This is not valid JSON.

You need to build an array, and then echo json_encode() (just once) after the loop.

Also your elseif should be this:

elseif ($row->status == "Fail" || $row->status == "Pending")

Upvotes: 3

Gaurav
Gaurav

Reputation: 28775

Replace elseif ($row->status == "Fail" || "Pending") { with

elseif ($row->status == "Fail" || $row->status == "Pending") {

You are missing $row->status == in your second condition of elseif block

Upvotes: 1

Related Questions