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


Fatal error: "Call to a member function prepare() on a non-object"

当我运行登录时,它给出了此错误:

致命错误:在第 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 {

首先进行此修复:

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

现在添加此调整:

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

这将强制连接为mysqli类,并且在未设置的情况下,它将在更接近问题根源的地方抛出致命错误。

您仍然需要找出失败的原因。我怀疑您的数据库凭据不正确,或者您在调用此函数时根本没有设置连接?