12

我正在尝试为我的网站构建一些功能,其中一些功能包括从 mysql 数据库中获取数据。当我在函数之外测试代码时,它似乎工作正常。所以这里是第一页:

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

$email = 'sample@gmail.com';

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

现在 db.php :

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

和functions.php文件:

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

我在访问第一个文件时遇到的错误是:

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

所以我需要/包含了 db.php,其中 $db 是 mysqli 连接。在同一个文件(第一个文件)中,我调用位于 functions.php 的函数

提前谢谢你,我会很感激你的帮助,因为这让我很生气......

4

2 回答 2

22

您可能需要使用global关键字,否则$db在本地范围内被视为 var。

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;
}
于 2012-05-31T14:59:29.467 回答
0

尝试在函数内部进行连接,在包含函数之前需要包含连接。

像这样的东西:

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;
}
于 2012-05-31T15:00:33.990 回答