Search code examples
phpsqlcodeigniterif-statementcodeigniter-3

Codeigniter3 filter query results to keep rows where a column value is not one of two values


I have a Codeigniter website where I am displaying some values using a foreach(). I am trying to ignore specific values from database.

I wrote the following code:

$res="select * from paymentform order by id desc limit 1000";
$query = $this->db->query($res);
foreach ($query->result_array() as $re) {
    if($re['authstatus']!='success' || $re['authstatus']!='0300'){
        // some processing
    }
}

The issue is that the columns containing success or 0300 are not being filtered out.


Solution

  • The problem with filtering in PHP (after you have limited the total rows to 1000) is that your resultant array will have an inconsistent number of rows.

    If you build your filtration logic into your query, you will have a better chance of hitting that 1000 limit. As others have mentioned, you made a basic mistake in your condition logic regarding "and" and "or" operators. An authstatus of 0300 satisfies the first condtion ($re['authstatus']!='success').

    Let's avoid it altogether with a refined query using CI3's query builder methods.

    CI3 Model Code:

    $result = $this->db
        ->from("paymentform")
        ->where_not_in("authstatus", ["success", "0300"])
        ->order_by("id", "DESC")
        ->limit(1000);
        ->get()
        ->result_array();
    

    The select() method is not needed when you want to return all columns from the table. Now you can feed $result to your foreach() loop.