所以,我正在试验一个网络应用程序。我想要做的是通过将登录用户的id与'posts'数据库中的id匹配,在时间线中显示用户的帖子列表。
这是我的模特
public function load_posts($user_id)
{
$this->db->where("user_id",$user_id);
$query=$this->db->get('posts');
if ($query->num_rows()>0)
{
foreach($query->result() as $rows)
{
$haha = array(
'post_id' => $rows->id,
'title' => $rows->title,
'artist' => $rows->artist,
'album' => $rows->album,
'caption' => $rows->caption,
);
}
return $haha;
}
return array();
}
我的控制器
public function welcome()
{
$data['title']= 'Welcome';
$user_id=$this->session->userdata('user_id');
$haha['hah'] = $this->user_model->load_posts($user_id);
$this->load->view('header_view',$data);
$this->load->view('welcome_view.php', $haha);
$this->load->view('footer_view',$data);
}
和视图
<div class="timeline">
<div class="boxes">
<table>
<?php
foreach($hah as $rows):
?>
<tr>
<td><?php echo $rows['title']; ?></td>
<td><?php echo $rows['artist']; ?></td>
<td><?php echo $rows['album']; ?></td>
<td><?php echo $rows['caption']; ?></td>
</tr>
<?php
endforeach;
?>
</table>
</div>
</div>
使用这些代码,我得到4行这些错误
A PHP Error was encountered
Severity: Warning
Message: Illegal string offset 'title'
Filename: views/welcome_view.php
Line Number: 25
2
A PHP Error was encountered
Severity: Warning
Message: Illegal string offset 'artist'
Filename: views/welcome_view.php
Line Number: 26
2
A PHP Error was encountered
Severity: Warning
Message: Illegal string offset 'album'
Filename: views/welcome_view.php
Line Number: 27
2
A PHP Error was encountered
Severity: Warning
Message: Illegal string offset 'caption'
Filename: views/welcome_view.php
Line Number: 28
2
以防万一需要,我的'帖子'表
CREATE TABLE IF NOT EXISTS `posts` (
`id` int(11) NOT NULL,
`title` varchar(255) NOT NULL,
`artist` varchar(255) NOT NULL,
`album` varchar(255) NOT NULL,
`cover` varchar(30) NOT NULL,
`caption` text NOT NULL,
`user_id` int(11) NOT NULL,
`postTime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
)
任何帮助都会非常感激!
答案 0 :(得分:0)
您返回的结果数组未使用您希望它们显示的键,但您尝试访问它们。熟悉Codeigniter中的返回结构的最佳方法是阅读文档,或者如果您是一个更加肮脏的&#39;像我一样输入,只需在返回语句之前在模型中放置一个var_dump($haha)
。
答案 1 :(得分:0)
您是否打开了探查器?您是否看到正在生成的正确查询?
你需要翻转你拥有的东西。
$this->db->where("user_id", $user_id);
$query = $this->db->get('posts');
或者您可以使用get_where
$query = $this->db->get_where('posts', array('user_id' => $user_id));