Below is my code under db.php
<?php
$con = mysqli_connect('localhost', 'root', '', 'mydb');
/* check connection */
if (!$con) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
?>
Under index.php I include db.php and functions.php as:
include("includes/db.php");
include("includes/functions.php");
functions.php is also using the db.php connection. I don’t have problem before when using mysql. But after I change mysql to mysqli I got an error “Warning: mysqli_query() expects parameter 1 to be mysqli, null given in” in my functions.php.
This is the function under functions.php that has an error:
function get_type($r_id){
$result=mysqli_query($con, "select type from rooms where id=$r_id") or die("select type from rooms where id=$r_id"."<br/><br/>".mysqli_error());
$row=mysqli_fetch_assoc($result);
return $row['type'];
}
My solution is to add db.php in every function under functions.php that calls mysqli like:
function get_type($r_id){
include("includes/db.php");
$result=mysqli_query($con, "select type from rooms where id=$r_id") or die("select type from rooms where id=$r_id"."<br/><br/>".mysqli_error());
$row=mysqli_fetch_assoc($result);
return $row['type'];
}
I am wondering if this is the correct solution.
The problem is that $con is not available to your functions
You can add another argument to each function
and then pass $con into it
OR
You can make $con accessible to each function by adding this
global $con;for exampleThe choice my friend.. is yours
(there may be other ways to skin this cat)