Fatal error: calling function-member-function () on null

I'm not sure what is going on here. I just followed the online tutorial and these errors appeared.

I get 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.'; } } ?> 
+6
source share
2 answers

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

 global $db; 

And I think when you wrote:

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

what you really wanted:

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

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

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

that way .. it should work ..

0
source

Source: https://habr.com/ru/post/989565/


All Articles