This question already has an answer here:
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
</div>
$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;
...
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.