phpmysqlphp-5.2

How to return 0 when the query return NULL


My php query look like:

<?php 
$raw_results = mysql_query("SELECT Operator, Data_przegladu, IFNULL(COUNT( Operator ),0) AS operator_count 
                            FROM przeglad 
                            WHERE MONTH(Data_przegladu) = 1 
                              AND Operator = \"Adrian Pikus\" 
                            HAVING (COUNT( Operator ) > 1)") or die(mysql_error());       
$row = mysql_fetch_array($raw_results);
echo $row['operator_count'];
?>

The result is NULL but i want the result to be 0. Somebody can help me? I use PHP 5.2 and i can't update it


Solution

  • I think the null coalescing operator should do the trick:

    For php 7 and above

    echo $row['operator_count'] ?? 0;
    

    Works for all versions

    echo $row['operator_count'] ? $row['operator_count'] : 0;
    

    Both will print $row['operator_count'] if it is not null else 0;