-1

I'm trying to display the number of rows in a SQL table with a condition.

The table viaturas has 4 records. I want to count how many rows in the column estado match "Inoperacional", in this case, 3 records.


I've created a function ViaturasInop() in viaturas.php:

<?php
    function ViaturasInop()
    {   
        require_once "config.php";

        $query = "SELECT * FROM `viaturas` WHERE `estado` LIKE 'Inoperacional'";

        if ($result=mysqli_query($link,$query))
        $rowcount=mysqli_num_rows($result);

        return $rowcount;

        mysqli_close($link);
    }

    echo ViaturasInop();
?>

If run viaturas.php it correctly returns 3.


In the page I want the result to be shown index.php in the HTML body I have the following to call the function:

<div class="h5 mb-0 font-weight-bold text-gray-800"><?php echo ViaturasInop(); ?></div>

However in return I get the following errors:

Notice: Undefined variable: link in C:[...]\php\viaturas.php on line 8

Warning: mysqli_query() expects parameter 1 to be mysqli, null given in C:[...]\php\viaturas.php on line 8

Notice: Undefined variable: rowcount in C:[...]\php\viaturas.php on line 11


I've tried other alternatives, however, I always get the same error.

Your Common Sense
  • 156,878
  • 40
  • 214
  • 345

1 Answers1

1

You should never use require_once to obtain a mysqli connection in a function.

First of all, it will work only once, as the name suggests.

Besides, even if you overcome this limitation, creating a new connection in every function call will destroy your database server.

Instead, you must call require_once "config.php"; once at the top of your script, and then use the $link variable to obtain the mysqli connection. In order to have the connection in a function you must pass it as a function parameter:

<?php
function ViaturasInop($link)
{   
    $query = "SELECT count(*) FROM `viaturas` WHERE `estado` = 'Inoperacional'";
    $result=mysqli_query($link,$query);
    $row = mysqli_fetch_row($result);
    return $row[0];
}

now, in your index file, somewhere at the top add

require_once "config.php";

and then put

echo ViaturasInop($link);

wherever you need the number

Your Common Sense
  • 156,878
  • 40
  • 214
  • 345
  • 1
    On a side note, you should never use mysqli_num_rows to count rows in the table. only SELECT count(*) query must be used for the purpose – Your Common Sense Mar 25 '20 at 08:18