我的应用程序中有一个模型:
public function get_news()
{
....
$this->load->database();
$top_news = $this->db->query("SELECT * FROM News ");
if ($top_news->num_rows())
{
$top_news = $top_news->result();
$top_news['AuthorInfo'] = $this->get_author($top_news['Userid']);
$this->cache->save('home.top_news', $top_news, 600);
}
else
{
$this->cache->save('home.top_news', NULL, 600);
}
}
return $top_news;
}
public function get_author($author_id)
{
$this->load->database();
$author = $this->db->query("SELECT * FROM AdminUsers WHERE id=? LIMIT 1", array($author_id));
if ($author->num_rows())
{
$author = $author->row_array();
}
else
{
$author = NULL;
}
return $author;
}
我得到了错误:
Message: Undefined index: Userid
但是这个字段存在于我的数据库的表News中。
我不明白我的问题在哪里。
请帮帮我,伙计们
我写var_dump,得到
Array
(
[0]=>stdClass object
(
[id]=>56
[Userid]=>4
...
使用这个查询,您将获得一个结果集(0、1或更多行),而不是一行:
$top_news = $this->db->query("SELECT * FROM News ");
你需要循环遍历结果。
foreach ($top_news->result_array() as $row)
{
$row['AuthorInfo'] = $this->get_author($row['Userid']);
$this->cache->save('home.top_news', $row, 600);
}
如果您确定只接收一行,或者只想选择第一行,您可以使用:
$row = $top_news->row_array();
$row['AuthorInfo'] = $this->get_author($row['Userid']);
$this->cache->save('home.top_news', $row, 600);
$top_news
是一个对象,而不是一个数组,如果您想获得第一个用户id,那么您需要获得位于$top_news[0]
中的用户id。
所以改变
$this->get_author($top_news['Userid']);
$this->get_author($top_news[0]->Userid);
你应该首先得到所有的新闻和循环设置AuthorInfo
和保存缓存result
你的查询应该像这样:
$query = $this->db->query("SELECT * FROM News");
$top_news = $query->result_array();
foreach($top_news as &$row)
{
$row['AuthorInfo'] = $this->get_author($row['Userid']);
}
$this->cache->save('home.top_news', $top_news, 600);