Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
582 views
in Technique[技术] by (71.8m points)

php - mysqli/mysql query inside function not working

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 = '[email protected]';

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:xampphtdocsauctiorincfunctions.php on line 6

Fatal error: Call to a member function query() on a non-object in C:xampphtdocsauctiorincfunctions.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......

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...