Fatal error: Call to a member function fetch() on boolean by reading records from database

Fatal error: Call to a member function fetch() on boolean by reading records from database

我有 readOne 功能。此函数将只读取类别 table 中的一条记录,并将值分配给名称和描述变量。它看起来像这样:

public function readOne($id) {
    $stmt = $this->conn->prepare('SELECT name, description FROM categories WHERE id = '.$id)->execute();
    $result = $stmt->fetch(PDO::FETCH_ASSOC);
    $this->name = $result['name'];
    $this->description = $result['description'];
}

我正在尝试使用这个来调用它:

<?php
if($_SERVER['REQUEST_METHOD'] == 'POST'){
if ( isset( $_POST['read'], $_POST['id']) ) {

    $cat = new Category($conn);

    $id = filter_input ( INPUT_POST , 'id', FILTER_SANITIZE_NUMBER_INT );


    echo $cat->readOne($id);
}}
?>
<div>
<h3>readOne():</h3>
<form action="" method="post">
<label>Category id :</label>
<input type="text" name="id" id="id" required="required" placeholder="Please Enter Id"/><br /><br />
<input type="submit" value="read" name="read"/><br />
</div>

但我收到错误:"Fatal error: Call to a member function fetch() on boolean" 在这一行:

$result = $stmt->fetch(PDO::FETCH_ASSOC);

编辑:连接代码:

<?php

class Database {

public function getConnection() {
    $result = false;
    try {
        $result = new PDO('mysql:host=localhost;dbname=demo', 'root', '');
    } catch(PDOException $e) { }
    return $result;
}
}
$db = new Database();
$conn = $db->getConnection();
if (!$conn) {
die("Error connecting to the database");
}

?>

您正在为 $stmt 分配 execute() 的 return 值。您需要将行 $stmt = $this->conn->prepare('SELECT name, description FROM categories WHERE id = '.$id)->execute(); 替换为:

$stmt = $this->conn->prepare('SELECT name, description FROM categories WHERE id = '.$id);
$stmt->execute();

查询执行代码需要如下更改:-

$stmt = $this->conn->prepare('SELECT name, description FROM categories WHERE id = "'.$id.'"'); 
$stmt->execute(); 
$result = $stmt->fetch(PDO::FETCH_ASSOC); 
$this->name = $result['name'];

在接受答案 (But now when i'm clicking "read" button nothing happens?) 后,将此代码用于您当前提出的问题:-

<?php
session_start();
if($_SERVER['REQUEST_METHOD'] == 'POST'){
if ( isset( $_POST['read'], $_POST['id']) ) {

    $cat = new Category($conn);

    $id = filter_input ( INPUT_POST , 'id', FILTER_SANITIZE_NUMBER_INT );


    $_SESSION['description'] =  $cat->readOne($id);
}}
?>
<div>
<h3>readOne():</h3>
<form action="" method="post">
<label>Category id :</label>
<input type="text" name="id" id="id" required="required" placeholder="Please Enter Id"/><br /><br />
<input type="submit" value="read" name="read"/><br />
</div>
<div class= "description"><?php if(isset($_SESSION['description']) && !empty($_SESSION['description'])){ echo $_SESSION['description'];}?></div>