php - Can't connect to database when code is moved to a function -
this question has answer here:
- php function use variable outside 3 answers
i want make function counts total of user in database.
$count = "select count(userid) user "; $run=mysqli_query($con,$count); $result = mysqli_fetch_array($run); echo $result[0];
the code above works fine. however, when put inside function:
<?php include("db.php"); function popo() { $count = "select count(userid) 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 mysqli, null given in c:\xampp\htdocs\admin\includes\function.php on line 5
warning: mysqli_fetch_array() expects parameter 1 mysqli_result, null given in c:\xampp\htdocs\admin\includes\function.php on line 6
$con
doesn't exist inside function, outside it.
you either pass $con
function this:
function popo($con) ... popo($con);
or make global (but not great style):
function popo() { global $con; ...
Comments
Post a Comment