从数据表的查询返回 NULL


Returning NULL from query for datatables

我想知道最好怎么做。现在我正在运行一个查询以查看我是否返回任何结果,如果没有返回,则返回 NULL。

在我的控制器上,我将结果集(无论是对象还是 NULL)发送到我的表,它会回显视图页面上的行。

对于我的表,我正在使用jquery数据表插件。我试图弄清楚当发送的值为 NULL 时如何让它处理数据,这样当它命中我的 foreach 循环时它就不会向我显示错误。

控制器:

$news_articles = $this->news_model->get_news_articles();
$this->data['news_articles'] = $news_articles;

型:

/**
 * Get news articles
 *
 * @return  object
 */
function get_news_articles()
{   
    $query = $this->db->get($this->news_articles_table);
    if ($query->num_rows() > 0) return $query->result();
    return NULL;
}

视图:

$tmpl = array ( 'table_open'  => '<table class="table" id="newsarticles-table">' );
$data = array('name' => 'newsarticles', 'class' => 'selectall');
$this->table->set_heading(form_checkbox($data), 'ID', 'Date', 'Title');            
$this->table->set_template($tmpl);             
foreach ($news_articles as $row)
{
    $checkbox_data = array(
        'name'        => 'newsarticles',
        'id'          => $row->id
    );
    $this->table->add_row(form_checkbox($checkbox_data), $row->id, $row->date_posted, $row->article_title);
}
echo $this->table->generate(); 

我通常使用 JSON 进行响应,然后添加一个"成功"类型的布尔值,然后在尝试处理任何数据之前检查该值。 它还允许在出现问题时轻松在响应中放置错误消息。

只是另一个想法

function get_news_articles()
{   
    $query = $this->db->get($this->news_articles_table);
    if ($query->num_rows() > 0) return $query->result();
    return FALSE;
}

控制器

$news_articles = $this->news_model->get_news_articles();
if(!$news_articles) $this->data['success'] = FALSE;
else
{
    $this->data['news_articles'] = $news_articles;
    $this->data['success'] = TRUE;
}

在视图中

if($success)
{
    foreach ($news_articles as $row)
    {
        //....
    }
}
else echo "No results found !";

如果没有结果,只需从模型中返回一个空数组。这样你的前辈就不会坏了。它只是不会循环任何东西。