我正在尝试为我的网站构建一些功能,其中一些功能包括在内 从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 connect。在同一个文件(第一个文件)中,我调用了functions.php中的函数
提前谢谢你, 我很感激你的帮助,因为这让我很生气......
答案 0 :(得分: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;
}
答案 1 :(得分: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;
}