我已经阅读了一个函数。该函数将从类别表中只读取一条记录,并将值分配给名称和描述变量。它看起来像这样:致命错误:通过读取数据库中的记录调用函数fetch()来获取布尔值
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>
,但我得到一个错误:布尔调用一个成员函数取():“致命错误“在这一行:
$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");
}
?>
@anant使用'isset()'与多个参数是好的。此外,'execute()'返回一个布尔值,所以你不能做你的建议。 – MrCode
@MrCode你是对的。谢谢 –