I have a page on my site which includes 2 SQL queries, one that inserts a row and another that updates a row. They work on different tables, and occasionally there is an error/crash that causes the first table to be marked as crashed so the insert query fails, but the second (update) query is still executed as that table is usually unaffected. This can cause problems on the site, so is there a way to prevent the second query from being run if an error occurs while executing the first query?
Yes. Take a look at the example at: http://www.w3schools.com/php/php_mysql_insert.asp. That example has the error displayed using mysqli_error, but you might want to deal with it differently. If you aren't using mysqli yet (see: http://marc.info/?l=php-internals&m=131031747409271&w=2) you could do something like: if (mysql_query($query)) { // Second update query mysql_query($query2) } else { echo "Error inserting record to first table: ".mysql_error(); } But, what is causing the insert on the first table to crash? Is there anything you can do in terms of better validation to prevent that happening in the first place?
I think that it's better to use transactions ... For example when using framework Codeigniter: $this->db->trans_start(); $this->db->query('AN SQL QUERY...'); $this->db->query('ANOTHER QUERY...'); $this->db->query('AND YET ANOTHER QUERY...'); $this->db->trans_complete(); PHP: It's a lot better, because if any query fails, there will be rollback which would revert any changes in database to previous state.
Yes, Go for transactions like Jelenik suggested. The database will take care of rolling back if any one of the query fails for any reason.