致命错误:“在非对象上调用成员函数prepare()”

时间:2015-01-11 09:16:58

标签: php mysqli

当我运行登录时,会出现此错误:

  

致命错误:在第30行的/home/lankaf5/public_html/admin/admin/functions.php中调用非对象的成员函数prepare()

我已经标记了它所指的第30行;请有人请检查并告诉我哪里错了?我尝试了所有可能的方法,但无法理解。

  // Create connection
  $conn = new mysqli($servername, $username, $password, $dbname);
  // Check connection
  if ($conn->connect_error) {
      die("Connection failed: " . $conn->connect_error);


 function login($email, $password, $conn) {;
    $sql ="SELECT id, username, password, salt FROM members WHERE email = ? LIMIT 1";
    // Using prepared statements means that SQL injection is not possible. 
    if ($stmt = $conn->prepare($sql)) { // line 30 that the error is referring to
        $stmt->bind_param('s', $email);  // Bind "$email" to parameter.
        $stmt->execute();    // Execute the prepared query.
        $stmt->store_result();

    // get variables from result.
    $stmt->bind_result($user_id, $username, $db_password, $salt);
    $stmt->fetch();

    // hash the password with the unique salt.
    $password = hash('sha512', $password . $salt);
    if ($stmt->num_rows == 1) {
        // If the user exists we check if the account is locked
        // from too many login attempts 

        if (checkbrute($user_id, $conn) == true) {
            // Account is locked 
            // Send an email to user saying their account is locked
            return false;
        } else {

1 个答案:

答案 0 :(得分:0)

首先进行此修复:

function login($email, $password, $conn) {; // <-- remove the semi-colon

现在添加此调整:

function login($email, $password, mysqli $conn) {

这将强制连接成为mysqli类,并且在未设置的情况下,它将在问题来源附近发出致命错误。

你仍然需要找出为什么这是失败的。我怀疑您的数据库凭据不正确,或者您在调用此函数时可能还没有设置连接?