0

I want to make a function that counts the total of user in the database.

$count = "SELECT COUNT(userid) FROM user ";
$run=mysqli_query($con,$count);
$result = mysqli_fetch_array($run);
echo $result[0];

The code above works fine. However, when I put it inside a function:

<?php
include("db.php");

function popo()
{
    $count = "SELECT COUNT(userid) FROM user ";
    $run=mysqli_query($con,$count);
    $result = mysqli_fetch_array($run);
    echo $result[0];
}
?>

<?php
popo();
?>

The following errors appear:

Warning: mysqli_query() expects parameter 1 to be mysqli, null given in C:\xampp\htdocs\admin\includes\function.php on line 5

Warning: mysqli_fetch_array() expects parameter 1 to be mysqli_result, null given in C:\xampp\htdocs\admin\includes\function.php on line 6

Marcos Dimitrio
  • 6,651
  • 5
  • 38
  • 62
fdfdfd
  • 501
  • 1
  • 7
  • 21

2 Answers2

1

The variable $con isn't in the scope of function popo(). What you could do is use the global command:

function popo()
{
    global $con;
    // ...

Be advised though that using globals like that is a bad practice in programming.

Marcos Dimitrio
  • 6,651
  • 5
  • 38
  • 62
0

$con doesn't exist inside the function, only outside it.

You could either pass $con to the function like this:

function popo($con)
...
popo($con);

or you could make it global (but this is not great style):

function popo() {
  global $con;
  ...
Matt Parlane
  • 453
  • 2
  • 11