Show 'No Data'或空白时,没有数据在mysql表,php, html


Show 'No Data' or blank when there are no data in mysql table, php, html

我的问题是关于mysql, php, html。我有MVC,

下面是我的控制器

public function index(){
    $this->load->model('user/model_user');
    $this->load->model('admin/model_admin');
    $view_all['news_array'] = $this->model_user->view_news();
    $view_all['users_array'] = $this->model_admin->view_users();
    $view_all['latestnews'] = $this->model_user->view_latestnews();
    $view_all['newscomments'] = $this->model_user->view_newscomments($view_all['latestnews']->news_id);
    $view_all['newstags'] = $this->model_user->view_newstags($view_all['latestnews']->news_id);
    $this->load->view('user/view_home',$view_all);
}

以上所有数组数据都是通过我的模型获取的下面是模型

function view_latestnews()
{
    $this->db->join('sc_users', 'sc_users.user_id = sc_news.news_postedby');
    $this->db->where('news_postedon = (SELECT max(news_postedon) FROM  sc_news)', NULL, FALSE);
    return $this->db->get('sc_news')->row();
}

下面是其中一行从我的视图(html),

<?php echo $latestnews->news_content;?>

当数据库中有数据时,这是预期的,意味着模型从DB中获得一些行,

但是当没有数据时,我的视图页面显示如下错误信息,

A PHP Error was encountered
Severity: Notice
Message: Trying to get property of non-object
Filename: user/view_home.php
Line Number: 115

当没有行可显示时,我们如何显示无数据或空白?

谢谢先进,

稍微修改一下模型函数

function view_latestnews()
{
  $this->db->join('sc_users', 'sc_users.user_id = sc_news.news_postedby');
  $this->db->where('news_postedon = (SELECT max(news_postedon) FROM  sc_news)', NULL, FALSE);
  $newsrow = $this->db->get('sc_news')->row();
  $nonews = new stdClass();
  $nonews->news_content = 'No news found';
  return ($newsrow) ? $newsrow : $nonews;
}

在您看来,只需使用:

if (is_object($latestnews)) {
echo $latestnews->newscontent;
}

一个更干净的解决方案(稍微修改@Gopakumar Gopalan的答案)

将检查$newsrow是否存在,如果存在则返回$newsrow,否则返回false,如下所示:

function view_latestnews() {
    ...
    return $newsrow ? $newsrow : false;
}

如果newsrow为空,则返回false,从而为您提供一个值。

在你的代码中显示最新消息:

<?php
if (!$newsrow) { //no news found
    echo '<div class="no-news">No news found!</div>'
} else {
    //Do stuff here with news object.
}
?>

简单地检查一个假值解决您的问题。注:

我没有使用codeIgniter的经验,可能是->row()函数返回一个空对象,如果行是空的。如果是这种情况,那么我所做的修改将不起作用,因为它仍然是一个求值为true的值。

祝你好运!

希望这能给你一些启发:

public function check_user($user_id=NULL)
    {
        $query = null; //emptying in case 
        $query = $this->db->get_where('api_users', array(//making selection
            'id' => $user_id,
        ));
        $count = $query->num_rows(); //counting result from query
         //when $count has rows then return your result otherwise 0 or any thing 
        if ($count === 0) {
           return 0;
        }
           return $query->row_array();
    }