php 致命错误:在 null 上调用成员函数 query()

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30992830/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 22:11:21  来源:igfitidea点击:

Fatal error: Call to a member function query() on null

phpmysqlsqldatabase-connection

提问by MPStimpson

I'm not sure what's going wrong here. I was just following a tutorial online and these errors popped up.

我不确定这里出了什么问题。我只是在网上学习教程,这些错误突然出现。

I'm getting the following errors

我收到以下错误

Error

错误

Notice: Undefined variable: db in C:\xampp\htdocs\wisconsindairyfarmers\admin\login.php on line 7

Fatal error: Call to a member function query() on null in C:\xampp\htdocs\wisconsindairyfarmers\admin\login.php on line 7

Code

代码

<?php
$db = new mysqli('127.0.0.1', 'root', '', 'wisconsindairyfarmers');
?>

<?php
require '../db/connect.php';
require '../functions/general.php';

    function user_exists($username){
        //$username = sanitize($username);
        $result = $db->query("SELECT COUNT(UserId) FROM users WHERE UserName = '$username'");
        if($result->num_rows){
        return (mysqli_result($query, 0) == 1) ? true : false;
    }}

if(empty($_POST) === false){

    $username = $_POST['username'];
    $password = $_POST['password'];

    if(empty($username) === true || empty($password) === true){ 
        echo 'You need to enter a username and password';
    }
    else if(user_exists($username) === false) {
        echo 'We can\'t find that username.';
    }
}

?>

回答by Juan Carlos Alvez Balbastro

First, you declared $db outside the function. If you want to use it inside the function, you should put this at the begining of your function code:

首先,您在函数外声明了 $db。如果你想在函数内部使用它,你应该把它放在你的函数代码的开头:

global $db;

And I guess, when you wrote:

我猜,当你写道:

if($result->num_rows){
        return (mysqli_result($query, 0) == 1) ? true : false;

what you really wanted was:

你真正想要的是:

if ($result->num_rows==1) { return true; } else { return false; }

回答by john paul ouseph benedicta

put this line in parent construct : $this->load->database();

将此行放在父结构中: $this->load->database();

function  __construct() {
    parent::__construct();
    $this->load->library('lib_name');
    $model=array('model_name');
    $this->load->model($model);
    $this->load->database();
}

this way.. it should work..

这样..它应该工作..