問題描述
我正在嘗試為我的網站構建一些功能,其中一些包括從mysql數據庫中獲取數據.當我在函數之外測試代碼時它似乎工作正常.所以在這里,第一頁:
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";
}
現在 db.php :
Now db.php :
$db = new MySQLi("localhost","test","test","test");
if ($db->connect_errno){
echo "$db->connect_errno";
}
還有functions.php文件:
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
所以我需要/包含了 db.php,其中 $db 是 mysqli 連接.在同一個文件(第一個文件)中,我調用位于 functions.php 的函數
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......
推薦答案
你可能需要使用 global
關鍵字,否則 $db
被認為是局部范圍內的 var.
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;
}
這篇關于函數內部的 mysqli/mysql 查詢不起作用的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!