函数内部的 mysqli/mysql 查询不起作用

mysqli/mysql query inside function not working(函数内部的 mysqli/mysql 查询不起作用)
本文介绍了函数内部的 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: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 查询不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

Warning: mysqli_query() expects at least 2 parameters, 1 given. What?(警告:mysqli_query() 需要至少 2 个参数,1 个给定.什么?)
INSERT query produces quot;Warning: mysqli_num_rows() expects parameter 1 to be mysqli_result, boolean givenquot;(INSERT 查询产生“警告:mysqli_num_rows() 期望参数 1 为 mysqli_result,给出布尔值;)
prepared statements - are they necessary(准备好的陈述 - 它们是否必要)
Do I need to escape my variables if I use MySQLi prepared statements?(如果我使用 MySQLi 准备好的语句,是否需要转义我的变量?)
Properly Escaping with MySQLI | query over prepared statements(使用 MySQLI 正确转义 |查询准备好的语句)
Is it possible to use mysqli_fetch_object with a prepared statement(是否可以将 mysqli_fetch_object 与准备好的语句一起使用)