Home » Php » SQL check rows for empty columns – compare them

SQL check rows for empty columns – compare them

Posted by: admin October 26, 2017 Leave a comment

Questions:

I want a list with columns that contains content.
So i try that. I will check each field in my database do figure out which of them has no content.

$arrAllField is a list of available fields

$strTable is the table where im looking in

    foreach ($arrAllField as $arrField)
            {
                $Result = $this->Database->prepare("SELECT * FROM ".$strTable." WHERE ".$arrField."  <> '' AND ".$arrField." IS NOT NULL ")->execute();
                while($Result->next())
                {   
                    $arrAllowedField[$arrField] = $arrField;    
                }
 }  

Oky but the problem is, i need to compare them, so that i only get back the columns where all rows contains content.

Maybe there is a better way to do that via SQL directly, like looking in the table and get only columns back where alle entries (rows) has content.

Best Regards

Peter

Answers:

You can try the following approach: check if the total number of records of the table is the same of the number of records where the value for that column has some content, as you say. This way, your query will look like this:

foreach ($arrAllField as $arrField) {
    $query = "SELECT (SELECT count($arrField) FROM `$strTable`) = (SELECT count($arrField) FROM `$strTable` WHERE $arrField <> '' AND $arrField IS NOT NULL) AS has_content";
    //Perform the query and process the result.
}

When executed, the query above returns a column named ‘has_content’ with value 1 if the column $arrField has all records with content or 0 if some record of the column $arrField has no content. Then you can process the result of the query the way you prefer by checking the value of the has_content column.

If you want to retrieve all the information at once instead of performing multiple queries and processing them, just create an array with the sub queries and concatenate them in a big one, like below:

$columnQueries = array();
foreach ($arrAllField as $arrField) {
    array_push($columnQueries, "(SELECT count($arrField) FROM `$strTable`) = (SELECT count($arrField) FROM `$strTable` WHERE $arrField <> '' AND $arrField IS NOT NULL) AS " . $arrField . "_has_content");
}
$finalQuery = "SELECT " . implode(", ", $columnQueries);
//Perform the $finalQuery and process the result.

This will return one line with the columns from $arrAllField concatenated with “_has_content”. The value for each column follow the same logic I mentioned before.

I hope this helps you.

Good luck.

Leave a Reply

Your email address will not be published. Required fields are marked *