我已經閱讀了一個函數。該函數將從類別表中只讀取一條記錄,並將值分配給名稱和描述變量。它看起來像這樣:致命錯誤:通過讀取數據庫中的記錄調用函數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你是對的。謝謝 –