Welcome Guest, Not a member yet? Register   Sign In
Help! Handling errors for empty db queries
#1

[eluser]Unknown[/eluser]
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!

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

Model:
Code:
function getArticle()
    {
        $this->db->from('news');
        $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;
        }
    }

View:
Code:
<?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;



Messages In This Thread
Help! Handling errors for empty db queries - by El Forum - 10-06-2012, 04:51 PM
Help! Handling errors for empty db queries - by El Forum - 10-06-2012, 05:17 PM



Theme © iAndrew 2016 - Forum software by © MyBB