Search code examples
phparrayscountreturn

PHP Returning an array in a function


I'm new to PHP MySqli and this is my first project. I'm trying to return a value from a function by placing in an array.

function riddor_dates($type,$id,$id1,$datatable,$date_from,$date_to){
    global $connection;
    $sql = "SELECT ".$id."  FROM ".$datatable." WHERE ".$id1." BETWEEN '".$date_from."' AND '".$date_to."' AND ".$id." = '".$type."'";

    if ($result = mysqli_query($connection,$sql)) {
        $count = 0;
        while ($row = mysqli_fetch_array($result)) {
            $count = ++ $count; 
        }
        echo "<br>".$type.": " .  $count;
        $counter[$type] = $count;
        return $counter;      
    }

    $type = 'RIDDOR - Major Injury';
    riddor_dates($type,$id,$id1,$datatable,$date_from,$date_to);
    var_dump($counter);

The function works to a point where it will print the result which is baically various counts for the array. However, i need to use the return in a table elsewhere but the var-dump just returns NULL.


Solution

  • As all the comment above - you are using $counter as if it global variable - if that is the case you can add global $counter at the begin of the function else if you want to use as return value you can add it to the function argument.

    Option 1 - use global variable

    function riddor_dates($type,$id,$id1,$datatable,$date_from,$date_to){
        global $connection;
        global $counter;
        $sql = "SELECT ".$id."  FROM ".$datatable." WHERE ".$id1." BETWEEN '".$date_from."' AND '".$date_to."' AND ".$id." = '".$type."'";
    
        if ($result = mysqli_query($connection,$sql)) {
            $count = mysqli_num_rows($result);
            echo "<br>".$type.": " .  $count;
            $counter[$type] = $count;     
        }
    }
    
    $type = 'RIDDOR - Major Injury';
    riddor_dates($type,$id,$id1,$datatable,$date_from,$date_to);
    var_dump($counter);
    

    Option 2 - use return value

    function riddor_dates($type,$id,$id1,$datatable,$date_from,$date_to){
        global $connection;
        $sql = "SELECT ".$id."  FROM ".$datatable." WHERE ".$id1." BETWEEN '".$date_from."' AND '".$date_to."' AND ".$id." = '".$type."'";
    
        if ($result = mysqli_query($connection,$sql)) {
            $count = mysqli_num_rows($result);
            echo "<br>".$type.": " .  $count;
            return $count;     
        }
    }
    
    $type = 'RIDDOR - Major Injury';
    $counter[$type] = riddor_dates($type,$id,$id1,$datatable,$date_from,$date_to);
    var_dump($counter);
    

    I strongly recommend the second option to avoid using global...