2016-04-03 27 views
2

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

?> 
+0

@anant使用'isset()'與多個參數是好的。此外,'execute()'返回一個布爾值,所以你不能做你的建議。 – MrCode

+0

@MrCode你是對的。謝謝 –

回答

0

查詢執行的代碼需要一些改變象下面這樣: -

$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> 
3

您正在分配$stmt,返回值爲​​。您需要更換線$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(); 
相關問題