我想显示数据,但总是获取试图获取非对象的属性”。
以下是html和php代码。
<h1><?php echo $data['post']->title; ?></h1>
<div class="bg-secondary text-white p-2 mb-3">
Written by <?php echo $data['user']->name; ?> on <?php echo $data['post']->created_at; ?>
</div>
<p><?php echo $data['post']->body; ?></p>
Posts控制器中的代码
public function show($id){
$post = $this->postModel->getPostById($id);
$user = $this->userModel->getUserById($post->user_id);
$data = [
'post' => $post,
'user' => $user
];
$this->view('posts/show', $data);
}
帖子模型中的代码
public function getPostById($id){
$this->db->query('SELECT * FROM posts WHERE id = :id');
$this->db->bind(':id', $id);
$row = $this->db->single();
return $row;
}
用户模型中的代码
public function getUserById($id){
$this->db->query('SELECT * FROM users WHERE id = :id');
// Bind value
$this->db->bind(':id', $id);
$row = $this->db->single();
return $row;
}
数据库安装程序类中的代码
// Execute the prepared statement
public function execute(){
return $this->stmt->execute();
}
// Get result set as array of objects
public function resultSet(){
$this->execute();
return $this->stmt->fetchAll(PDO::FETCH_OBJ);
}
// Get single record as object
public function single(){
$this->execute();
return $this->stmt->fetch(PDO::FETCH_OBJ);
}
我希望您能成功理解代码,因为我认为我的pdo无法正常工作,并且$ post是一个对象,但是我的函数single()应该将record作为对象返回,但它没有这样做。 / p>