简体   繁体   中英

query result using codeIgniter

It is the first time for me to use codeIgniter, I tried to build a simple DB driven application. First the model:

class News_model extends CI_Model {

public function __construct()
{
    $this->load->database();
}

public function get_news()
   {

    $query = $this->db->get('news');
    return $query->result_array();

   }
   }

second the controller

class News extends CI_Controller {

public function __construct()
{
parent::__construct();
$this->load->model('news_model');
}

public function index()
{
$data['news'] = $this->news_model->get_news();
$data['title'] = 'News archive';

$this->load->view('templates/header', $data);
$this->load->view('news/index', $data);
$this->load->view('templates/footer');
}

The view "index":

<?php foreach ($news as $news_item): ?>

 <h2><?php echo $news_item['title'] ?></h2>
 <div id="main">
    <?php echo $news_item['text'] ?>
 </div>
 <p><a href="news/<?php echo $news_item['slug'] ?>">View article</a></p>

<?php endforeach ?>

When I run the code it displays the header and the footer, but no database record is displayed. If I put a print statement in the view outside the foreach it works, but not inside the foreach. I use if($news) to find out if the query retrieved any result, but there is no result retrieved.

How can I know why there is no result retrieved from the DB?

You need to call another foreach inside your foreach. example:

foreach ($result as $row) {
        foreach ($row as $key => $val) {
            if ($key === "reservation_info") {
                $data['decoded'] = json_decode($val);
            } else {
                $data[$key] = $val;
            }
        }
    }

and i would use the '$val' values in the view. just by calling them as variables, like so

//in the view
echo $decoded
echo $firtname

... and so on

to check if new is empty or not, just

print_r($news);

or you can modify your view :

<?php if(!empty($new)): ?>
  <?php foreach ($news as $news_item): ?>

   <h2><?php echo $news_item['title'] ?></h2>
   <div id="main">
      <?php echo $news_item['text'] ?>
   </div>
   <p><a href="news/<?php echo $news_item['slug'] ?>">View article</a></p>

  <?php endforeach ?>
<?php else: ?>
  Empty news 
<?php endif; ?>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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