12

I'm tryin to build some functions for a website of mine and some of them consist in fetching data from the mysql database. When I test the code outside of the function it seems to work properly. So here it is, The first page:

require('db.php');
require('functions.php');

$email = 'sample@gmail.com';

if (user_exists($email) == true){
 echo "Good news, this exists";
}

Now db.php :

$db = new MySQLi("localhost","test","test","test");
if ($db->connect_errno){
    echo "$db->connect_errno";
}

And the functions.php file:

function sanitize ($data){
    $db->mysqli_real_escape_string($data);
}
function user_exists($usermail){
    $usermail = sanitize($usermail);
    $query = $db->query("SELECT COUNT(userId) FROM users WHERE userEmail= '$usermail' ");
    $check = $query->num_rows;
    return ($check == 1) ? true : false;
}

And the error I'm getting when accessing the first file is:

Notice: Undefined variable: db in C:\xampp\htdocs\auctior\inc\functions.php on line 6

Fatal error: Call to a member function query() on a non-object in C:\xampp\htdocs\auctior\inc\functions.php on line 6

SO I've required/included the db.php where $db is the mysqli connect. And within the same file(first file) I call the functions located at functions.php

Thank you in advance, I'd appreciate your help as this is pissing me off......

j0k
  • 22,600
  • 28
  • 79
  • 90
inrob
  • 4,969
  • 11
  • 38
  • 51

2 Answers2

22

You probably need to use the global keyword, otherwise $db is considered a var in local scope.

function sanitize ($data){
    global $db;
    $db->mysqli_real_escape_string($data);
}

function user_exists($usermail){
    global $db;
    $usermail = sanitize($usermail);
    $query = $db->query("SELECT COUNT(userId) FROM users WHERE userEmail= '$usermail' ");
    $check = $query->num_rows;
    return ($check == 1) ? true : false;
}
jeremyharris
  • 7,884
  • 22
  • 31
  • 1
    Oh thank you my friend :) You have no idea how much time I put on solving this silly problem :) You've saved my day. Thank you. – inrob May 31 '12 at 15:04
0

Try to connect inside the function, and connection needs to be included before you include functions.

Something like this:

function user_exists($usermail){
    $db = new MySQLi("localhost","test","test","test");
    $usermail = sanitize($usermail);
    $query = $db->query("SELECT COUNT(userId) FROM users WHERE userEmail= '$usermail' ");
    $check = $query->num_rows;
    return ($check == 1) ? true : false;
}
miszczu
  • 1,179
  • 4
  • 19
  • 39
  • Thanks for your suggestion. But I guess that wouldnt be a good idea to include the connection query in every single function. But thanks ;) – inrob May 31 '12 at 15:05