Search code examples
zend-framework2

How to check if a record was updating using Zend Framework's 2 Sql Adapter Class


I'm trying to test to see if an update query was successful with Zend Framework 2. I'm using the getAdapter()->query() methods but I'm unsure of how to actually test to see if anything was returned or if it actually executed. I know it is executing (as I can see the update working via mysql workbench) but I'm not sure on how to actually count or verify. Here is the code I have in place (which I know is wrong but I don't know what else to do):

 $update = $this->update->table('stores')
                ->set(array('number_of_items' => $number))->where(array('store_name' => $this->store_name));

 $query = $this->sql->getAdapter()->query($this->sql->buildSqlString($update), Adapter::QUERY_MODE_EXECUTE);

 if ($query->count() > 0) {
     // insert the items into the items table
    $insert = $this->insert->into('items')
        ->columns(array('store_id', 'price', 'description'))
        ->values(array($row['store_id'], $price, $item_desc));

    $query = $this->sql->getAdapter()->query(
        $this->sql->buildSqlString($insert),
        Adapter::QUERY_MODE_EXECUTE
    );

    if ($query->count() > 0) {
        return true;
    } else {
        throw new \Exception("Error adding your item to the items table, please try again.");
    }
} else {
    // this is the exception being thrown
    throw new \Exception("An error occurred while adding your item(s) to the store, please try again");
}

Now I know most likely count() will only work on select queries but I am unsure of how to test to see if the update and insert were successful.

Any help would be appreciated

Thanks


Solution

  • To test if update and insert were successful. As per your code

      try {
          $affetedRows = $this->insert->into('items')
                        ->columns(array('store_id', 'price', 'description'))
                        ->values(array($row['store_id'], $price, $item_desc));
                }catch (\Exception $e) {
                    var_dump($e->getMessage());exit; // see if any exaption Or error in query
                }
        }
    

    var_dump($affetedRows ) // it will return number of affected rows.

    Same for delete and update, after successfull execution delete and updateare also returns number of affected rows.

    so if there is successfull exceution, you can check success of your query.

    Thanks.