mysqli / mysql查询里面的函数不工作 [英] mysqli/mysql query inside function not working

查看:125
本文介绍了mysqli / mysql查询里面的函数不工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试着为我的网站构建一些功能,其中一些功能包括
从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:\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的函数

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......

推荐答案

您可能需要使用全局

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查询里面的函数不工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆