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


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


$db = new mysqli('', 'root', '', 'wisconsindairyfarmers');

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'");
        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.';

shareimprove this question
Your $db variable is inside a function and thus out of scope from the code that defines it. Declare it global, or better, pass it as an argument to your function. See the PHP manual on scope – user1864610 Jun 23 '15 at 2:22 
I changed the variables, and the first error is fixed, but I'm still getting : Fatal error: Call to undefined function mysqli_result() – MPStimpson Jun 23 '15 at 2:32
I think that is because you are using OOP on the first part and procedural for the the results. – Rasclatt Jun 23 '15 at 2:38
I'm kind of new to php, how do I go about fixing that? – MPStimpson Jun 23 '15 at 2:41
I think that's because mysqli_result() is not a function. I'm really not clear what that piece of code is trying to do, but mysqli_result() doesn't exist in PHP. – user1864610 Jun 23 '15 at 2:41

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:

global $db;

And I guess, when you wrote:

        return (mysqli_result($query, 0) == 1) ? true : false;

what you really wanted was:

if ($result->num_rows==1) { return true; } else { return false; }
shareimprove this answer
I'm not getting any errors anymore, but I can't seem to get into the 'user_exists($username) === false' when I'm testing do you have any other wisdom to share with me today :) – MPStimpson Jun 23 '15 at 4:08
Yes, your SQL query will always return 1 row, with 1 field saying the amount of users equals to username. Change that to "SELECT * FROM users WHERE UserName = '$username'" and it will work – Juan Carlos Alvez Balbastro Jun 24 '15 at 17:41
I figured that out, but thank you very much! You've been very helpful! That's what I get for blindly following tutorials – MPStimpson Jun 26 '15 at 1:06

블로그 이미지



댓글을 달아 주세요