繁体   English   中英

查询CodeIgniter中的未定义ID

[英]Undefined id in query CodeIgniter

我的应用程序中有一个模型:

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  

但是此字段存在于数据库中的“新闻”表中。
我不明白我的问题在哪里。
帮帮我,伙计们

我写了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);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM