• 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Help! Handling errors for empty db queries

So, I'm just getting started with codeigniter, and I've been using a handful of different tutorials to cobble something together...

I started out with a basic news page, where you can view a list of articles, and then the titles link to a page showing just that article. What I'm struggling with is sending users to a 404 page if they end up entering a URL for an article that doesn't exist.

http://localhost/news/articles/1 returns an article, because there's an entry in the db for it

http://localhost/news/articles/2 There's no entry in the db (yet) so it shows the php error below, where I was kind of expecting there to be a blank page

Quote:A PHP Error was encountered

Severity: Warning

Message: Invalid argument supplied for foreach()

Filename: views/newsarticle_v.php

Line Number: 4

So what I'd like to get to, is where the user is redirected to a 404 error (or just back to the index) instead. I'm sure there's a REALLY simple way to do this, but I've drawn a blank on the things I've tried.

Additionally, I'd much prefer to have the article title used in both the url and the pages <title> tags for SEO, but hell if I can figure out where to start with that one!

public function articles()
        $data['rows'] = $this->news_model->getArticle();
        $data['title'] = 'Article Page';
        $data['main_content'] = 'newsarticle_v';
        $data['hero'] = '0';
        $this->load->view('template', $data);

function getArticle()
        $this->db->where("id", $this->uri->segment(3));
        $query = $this->db->get();
        if($query->num_rows() > 0)
            foreach ($query->result() as $row)
                $data[] = $row;
        return $data;

<?php foreach($rows as $r) : ?>
    <div class="art-title"><h3>&lt;?php echo $r->title;?&gt;</h3></div>
    <div class="art-content">&lt;?php echo $r->full_text; ?&gt;</div>
&lt;?php endforeach; ?&gt;

At the bottom of your getArticle return FALSE. That way when the URL segment is not found you will have a way to test for it in your controller. Then in your controller if the model returns false, then use show_404() or load a different view or redirect to another page.
As for using the page title in the URL, you can use the URL helper function url_string() to convert it. Similar to WordPress you may want to save the slug in the database. Then lookup the slug rather than the id. Or in your model you could check if the segment is numeric then search by id otherwise search by the slug if it's a string.

Digg   Delicious   Reddit   Facebook   Twitter   StumbleUpon  

  Theme © 2014 iAndrew  
Powered By MyBB, © 2002-2021 MyBB Group.