Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

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

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 this:

$res = $mysqli->query("SELECT * FROM user WHERE user='$user' and password='$pw'");

This is login.php:

$user = $_POST['user'];
$pass = $_POST['pass'];
$pw = md5($pass); 
include_once('connect.php');

function check_login($user,$pw,&$result){
    $res = $mysqli->query("SELECT * FROM user WHERE user='$user' and password='$pw'");
    $cont = 0;
    while($row = $res->fetch_object()){
        $cont++;
        $result = $row;
    }
    if($cont == 1){
        return 1;
    }
    else{
        return 0;
    }
}

if(!isset($_SESSION['userid'])){
  if(isset($_POST['login'])){
    if(check_login($user,$pw,$result) == 1){
        session_start();
        $_SESSION['userid'] = $result->id_user;
        header("location:index.php?var=ok");
    }
    else{
        header('location:index.php?var=log');
    }
  }
}

And the code of connect.php :

$mysqli = new mysqli('localhost', 'root', 'pass', 'cms' );
if ($mysqli->connect_error) {
   die('Error de Conexión (' . $mysqli->connect_errno . ') '
        . $mysqli->connect_error);
 }

What could be the problem? Problems connecting the database?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...