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

后端 未结 5 2047
夕颜
夕颜 2020-12-21 17:11

I\'ve got this error:

Fatal error: Call to a member function query() on a non-object in /Applications/XAMPP/xamppfiles/htdocs/login.php on line 8

The line is

相关标签:
5条回答
  • 2020-12-21 17:49
    public function connectDB($DBServer, $DBUser, $DBPass, $DBName) {
                global $con;
                $con = new mysqli($DBServer, $DBUser, $DBPass, $DBName) or die ("Error occured");
                return $con;
    

    and then pass $con in all the functions that you define or run wherever.

    0 讨论(0)
  • 2020-12-21 17:57

    variable $mysqli in function check_login is out of scope (it is declare outside the function) so it is null.

    0 讨论(0)
  • 2020-12-21 17:58

    It looks like your $mysqli variable is not being set properly within the scope of your code thats executing the query. Can you confirm that $mysqli is indeed a mysqli object and not, say, set to null?

    You can check this by doing: echo print_r($mysqli); right before you call the ->query method in your code.

    If it is not set properly, track the variable backward in your code until you see why

    0 讨论(0)
  • 2020-12-21 18:03

    This is most likely a scoping issue. This means that the variable $mysqli that you define in your included file is outside of the check_login function's scope (i.e. is not known inside this function).

    You could try to get the $mysqli variable from global scope with

    function check_login($user,$pw,&$result){
        global $mysqli;
        $res = $mysqli->query("SELECT * FROM user WHERE user='$user' and password='$pw'");
        // ...
    

    Edit: Oh, and you should also mind the SQL injection vulnerabiliy in your code. Use prepared statements to prevent this issue (or at least escape your input variables with a function like mysqli::real_escape_string).

    0 讨论(0)
  • 2020-12-21 18:10
    function check_login($user,$pw,&$result){
        global $mysqli;
        $res = $mysqli->query("SELECT * FROM user WHERE user='$user' and password='$pw'");
        $cont = 0;
        while($row = $re[...]
    

    Mind the "global". This puts the var in the scope of your method. This is a quick and dirty solution, but will work in this case.

    0 讨论(0)
提交回复
热议问题