开发者

What am I doing wrong to get this fatal error

My Code:

<?php

$conn = new MySQLi("localhost", "root", "", "barman");

function validate_details($user, $pass){

$sql = "SELECT * FROM users";
$result = $conn->query($sql);

    if($user==$row->user && isset($user)){

        if($pass == $row->pass && isset($pass)){
            return true;
        }
    }else{
        return false;
    }


} 


?>

The error:

Fatal error: Call to a member function query() on a non-object in C:\xampp\htdocs\barman\assets\login\functio开发者_开发问答ns.php on line 8 (line 8 is $result = $conn->query($sql); )


you cannot used variables or objects outside your function except the ones that are globally set.

try to use

function validate_details($user, $pass){
    global $conn;
    ......................
}


You are trying to access a variable that was created in the global scope from within a function.

Either pass the $conn variable in as an argument to the function (this is the prefered option), or use the global keyword to import it into the function's scope.

So you could do: (prefered option)

function validate_details ($conn, $user, $pass) {
  // function code goes here
}

// Call the function like this
$result = validate_details($conn, 'myuser', 'mypass');

...or this... (not so good)

function validate_details ($user, $pass) {
  global $conn;
  // function code goes here
}

There are many reasons it is better to pass the connection object in as a parameter, but here are a couple:

  • It means you can use your function with more that one connection in the same script
  • It means you can easily recycle the function, unmodified, in other scripts
  • If at some point you need to rename the $conn variable in the global scope, you don't have to worry about changing it in the function

I suppose it's also worth mentioning the $GLOBALS array - this is a superglobal (i.e. it is available everywhere) that you could use instead, but in practice this is not much different from the global keyword and should generally be avoided for the same reasons.

You could use it like this:

function validate_details ($user, $pass) {
  // ...
  $result = $GLOBALS['conn']->query($sql);
  // ...
}


Use global $conn. Otherwise it won't work. :)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜