php - Can't connect to database when code is moved to a function -


this question has answer here:

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

Popular posts from this blog

c# - Binding a comma separated list to a List<int> in asp.net web api -

Delphi 7 and decode UTF-8 base64 -

html - Is there any way to exclude a single element from the style? (Bootstrap) -