2016-04-03 40 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(); 
相关问题