gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 01:52:59 25 4
gpt4 key购买 nike

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

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 :调用 bool 值上的成员函数 fetch()”:

$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() .您需要替换行 $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();

关于php - fatal error : Call to a member function fetch() on boolean by reading records from database,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36390337/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com