Fatal error: Uncaught Error: Call to a member function close() on bool

Fatal error: Uncaught Error: Call to a member function close() on bool

在我用于更新功能的库存管理应用程序中,设置 sql 后,我正在执行 $stmt,如果执行成功,我将前往主页。否则做一些其他的动作。在我准备 sql 命令并执行它的 if 语句中,我用 $stmt->close() 关闭 $stmt。但这给我带来了上面的错误。我遵循了其他一些问题的答案,他们建议在 if 语句中移动 close() 行。但是没用。

Update.php

    // Check input errors before inserting in database
    if(empty($itemname_err) && empty($itemnumber_err) && empty($cost_err)&& empty($details_err)){
        // Prepare an update statement
        $sql= "UPDATE inventory SET itemname=$itemname, itemnumber=$itemnumber, cost=$cost,details=$details, WHERE id = $id";
      
        if($stmt = $mysqli->prepare($sql)){
   
            // Set parameters
            $param_itemname = $itemname;
            $param_itemnumber = $itemnumber;
            $param_cost = $cost;
            $param_details = $details;
            $param_id = $id;
    
            //$stmt->bind_param("sssss", $param_itemname, $param_itemnumber, $param_cost, $param_details, $param_id);
            // Attempt to execute the prepared statement
            if($stmt->execute()){
                // Records updated successfully. Redirect to landing page
                header("location: index.php");
                exit();
            } else{
                echo "Oops! Something went wrong. Please try again later.";
            }
        }
        // Close statement
        $stmt->close(); // here's the problem line
    }
    // Close connection
    $mysqli->close(); 
    }else{
        ...
}

我尝试检查 sql,但我觉得没问题。那么有什么建议吗?

您使用的准备查询的概念完全错误。这个想法是您准备一个包含占位符的查询,而不是实际数据。从查询编译阶段删除数据,删除将错误代码注入 SQL.

的能力

您收到的错误是因为准备失败,因此您的代码跳转到 IF 之后的行,您在此处尝试向我们提供现在包含 FALSE 的 $stmt 变量,就好像它是一个对象一样,如果查询成功,它本来会是这样。

所以试试这个

    // Check input errors before inserting in database
    if( empty($itemname_err) && empty($itemnumber_err) && 
        empty($cost_err) && empty($details_err))
    {
        // Prepare an update statement
        $sql= "UPDATE inventory SET itemname=?, itemnumber=?, 
                                    cost=?, details=? 
                                    WHERE id = ?";
      
        $stmt = $mysqli->prepare($sql);
    
        $stmt->bind_param("sidsi", $itemname, $itemnumber, 
                                    $cost, $details, $id);
        // Attempt to execute the prepared statement
        if($stmt->execute()){
            // Records updated successfully. Redirect to landing page
            header("location: index.php");
            // these 2 are unnecessary but if they go anywhere it 
            // should be before the exit statement
            $stmt->close();
            $mysqli->close(); 

            exit();
        } else{
            echo "Oops! Something went wrong. Please try again later.";
        }
    }