phpcodeigniternullquery-builderresultset

Codeigniter- count number of null columns in a row


I want to count the number of columns from a single row where fields are null. I know this can be done in normal SQL statement. But I want to learn how to do that in CI.

Yes, I can do this for only one column using this statement:

$this->db->where('column_name' => NULL)

This is for single column. Do I have to do it for every column? Or I can do it in some better way.


Solution

  • If you are working on only one row as would be the case using the following query

    $row = $this->db
        ->get_where('table', ['id' => $value])
        ->row_array();
    

    Then you could count the NULL values in the $row array like this

    $count = 0;
    foreach ($row as $column)
    {
        if(! isset($column))
        {
            $count++;
        }
    }
    echo $count;
    

    The query depends on the id column having unique values.

    If you want to check more than one row let me know and I'll add that to the answer.