Prevent SQL query running if an error occurs while executing another query?

Discussion in 'PHP' started by conorod, Aug 3, 2013.

  1. #1
    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?
     
    conorod, Aug 3, 2013 IP
  2. tickedon

    tickedon Member

    Messages:
    34
    Likes Received:
    3
    Best Answers:
    0
    Trophy Points:
    48
    #2
    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?
     
    tickedon, Aug 3, 2013 IP
  3. Jelenik

    Jelenik Well-Known Member

    Messages:
    73
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    126
    #3
    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.
     
    Jelenik, Aug 7, 2013 IP
  4. samyak

    samyak Active Member

    Messages:
    280
    Likes Received:
    7
    Best Answers:
    4
    Trophy Points:
    90
    #4
    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.
     
    samyak, Aug 13, 2013 IP