我有readOne功能。此函数将只读取类别表中的一条记录,并为名称和描述变量赋值。它看起来像这样:
finished()
我试图用这个来打电话:
require_once('../config/Database.php');
class Category {
private $conn;
private $id;
private $name;
private $description;
private $created;
public function __construct($db) {
$this->conn = $db;
}
public function readOne($id) {
$stmt = $this->conn->prepare('SELECT name, description FROM categories WHERE id = "'.$id.'"');
$stmt->execute();
$result = $stmt->fetch(PDO::FETCH_ASSOC);
$this->name = $result['name'];
$this->description = $result['description'];
}
我没有收到任何错误,但在编写类别ID并按下按钮后,也没有发生任何事情,如何解决?
与数据库的连接:
<?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>
答案 0 :(得分:1)
您的readOne函数不返回任何内容。像这样改变readOne函数:
public function readOne($id) {
$stmt = $this->conn->prepare('SELECT name, description FROM categories WHERE id = "'.$id.'"');
$stmt->execute();
$result = $stmt->fetch(PDO::FETCH_ASSOC);
$this->name = $result['name'];
$this->description = $result['description'];
return $this->name.$this->description;
}
此函数现在返回一个带有名称和描述的字符串。
答案 1 :(得分:1)
你的readOne()
函数没有返回任何内容,因为没有return语句。
另请检查$id
不能为空。