0

I'm selecting a post from my DB table and I'm getting the id from the url with getParam(). What I want to do is, show an error message when there's no posts with the id specified in the url.

This is the query I have:

$db = Zend_Registry::get('db');
$select = $db->select();
$select->from(array('p' => 'posts'))
       ->join(array('u' => 'users'), 'u.user_id = p.post_userid')
       ->where('p.post_id = ?', $postid);
$post = $db->fetchRow($select);

Problem is, when i do echo count($post) it shows 1 even when the id is invalid, and it shows more than 1 when the id is valid and a row was actually selected.

So my question is, how should I check how many rows were selected with the id specified? ($postid!).

Any suggestions?

2 Answers2

1

If there are no results fetchRow will return false, so you can test directly on the result, like: if($post) { ... And this is the reason that count returns 1, calling count on anything other than an array returns 1 (except on a null variable). Note that this is different to the fetchRow method of Db_Table, that returs null.

user570783
  • 686
  • 4
  • 7
0

I think that you should change $post = $db->fetchRow($select); into $posts = $db->fetchAll($select);

Marcin
  • 215,873
  • 14
  • 235
  • 294
  • But I'm never expecting more then one row. If I do that, I'll also have to do something like `foreach($posts as $row)` which kind of complicates things. Isn't there any other way? –  Jan 28 '11 at 12:08
  • 1
    @Sled. $db->fetchRow($select); should return false if no row was found. Thus, you could just check if false === $post. – Marcin Jan 28 '11 at 12:16