Pregunta

I am currently using Doctrine's DBAL library for MySQL interfacing and have currently built a structure around:

public function update(array $data, $id)
{
    return $this->db->update($this->table, $data, array('id' => $id));
}

Which of course returns the number of affected rows. The issue now is that I perform certain actions after updates that should trigger upon a successful update. Under the current system if I was to "edit" a record (showing the form only) and immediately hit save it returns an error since I check the result of the update function above. This not only displays an error in my site but also prevents the other "successful update" actions from running.

Is there a way to see if an update failed to run outside of the affected rows? Can I just ignore this completely and assume the update will always work? Would trapping Exceptions be enough to catch any fatal errors?

¿Fue útil?

Solución

You can assume that update will always work. Exceptions will be thrown for major problems such as invalid field names or constraint violations. Consider making a few test cases just to convince yourself of this.

Be aware that no escaping is done with the update() method so it up to you cleanse your data.

Otros consejos

You can assume updates work for the most part but you probably want to look into Transactions, they are the best way of handling exceptions and maintaining DB integrity if something does go wrong. PHP doesn't provide conventional means of recovering from fatal errors for reasons outlined in this answers.

Under the current system if I was to "edit" a record (showing the form only) and immediately hit save it returns an error since I check the result of the update function above

Don't forget that $this->db->update() returns the number of the affected rows (or false on fail). If you just open "Edit" and click "Save", there will be no change of the data and "affected rows" will be 0. To return the success or fail of $this->db->update(...) you may use false !==

if ($myModel->update($data, $id)) {
    echo "success";
}

and in your myModel:

public function update(array $data, $id)
{
     return false !== $this->db->update(...);
}
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top