gardni
gardni

Reputation: 1424

zend get() single record returns exception instead of zero results

I have a very simple function in a zend skeleton that gets a row based on an ID you input. If you use an ID that it finds in the database it works fine:

$this->getTestimonialTable()->get($request->getPost('id'));

however if you put an id that doesn't exist, it returns an exception saying the row doesn't exist, which i know already.

I want it so, if it finds the row, continue as normal, if not show that there was no results, not raise an exception.

I've tried wrapping it in a count:

 if (count($this->getTestimonialTable()->get($request->getPost('id'))) > 0) {
     //more than 1 result
 } else {
     //zero results
 }

however the exception is still raised on the initial call, i also tried wrapping it in a try statement:

 try {
    $this->getTestimonialTable()->get($request->getPost('id'));
    //if im here i should have a result             
 } catch (Exception $e) {
     //zero results           
 }

Can anyone suggest what the problem is?


solved

So the principle was right, however i was running the code on the factory method, not running it on the database call.

so in my factory i now have

public function get($id)
 {
    $id  = (int) $id;
    $rowset = $this->tableGateway->select(array('id' => $id));
    $row = $rowset->current();

    if (!$row) {
        return null;
    }

    return $row;
 }

which then makes the above count work as intended

if (count($this->getTestimonialTable()->get($request->getPost('id'))) > 0) {
 //more than 1 result
} else {
     //zero results
}

Upvotes: 2

Views: 67

Answers (1)

Rayhan Muktader
Rayhan Muktader

Reputation: 2106

Zend is behaving as expected. You have asked it to return a row. It should do nothing more. So, it's throwing an exception when it can't return a row.

I want it so, if it finds the row, continue as normal, if not show that there was no results, not raise an exception.

Your best option is to put the database call in a try catch block, catch the exception and then parse the exception to determine if no rows were found.

Upvotes: 1

Related Questions