undefined variable

0 Kumi Festus · February 20, 2015
Guys I need help here. I don't  have the eyes to see this. I connected to a database like below:

$db_host = "localhost";
$db_username = "root";
$db_password = "";
$db_name = "db_name";

$db = new mysqli($db_host,$db_username,$db_password,$db_name);

And I referred to it in a query on a different page like below:
$query = $db->query("SELECT COUNT(`user_id`) FROM `users` WHERE `username` = '$username'");
return (mysqli_result($query,0)==1)? true:false;

I get this error: undefined variable db,
What am I doing wrong here?

Post a Reply


- page 2
Oldest  Newest  Rating
0 Kumi Festus · February 23, 2015
I have a folder containing all the functions,session,connection
includes/connect.inc.php //connects to database
includes/users.php //all functions
includes/general.php //functions to sanitize the functions
includes/init.php //contains sessions and all others

so the init.php has the following

include 'users.php';
include 'connect.inc.php';
include 'general.php';

and on the other pages that need to interact with the database with have the init.php, eg


Someone told me that I need a global varaible, like so;

$db = new mysqli("localhost","root","","db_name")

On the functions page I should declare something like below:

function email_exists($email){
global $db; //the global variable
$email = $_POST["email"];
$query = $db->query("SELECT COUNT(user_id) FROM tb WHERE email = '$email'");
return ($query->num_rows()===1) ? true:false;

I used the OOP method
0 Mitch Mullvain · February 23, 2015
Did you include the database page. I always do that.

BTW, by include I mean the following:

<?php include ("database.php"); ?>


Also declaring new is used on classes, so unless you have a mysqli class in your program, declare
$db = mysqli_connect($host, $user, $pass, $dbname);
  • 1
  • 2



Server-side, HTML embedded scripting language used to create dynamic Web pages.