Is it possible to execute a query (insert) and only then check if it is duplicate?

5

I am reading an XML file and at the same time I insert the records into the DB.

My code looks like this:

foreach($itens as $item)
{
    ...
    if ( ! $stmt_insert_item->execute ( ) ) 
    {
    if ( $this->mysqli->errno == ER_DUP_ENTRY ) // se for uma entrada duplicada
        continue;
    else
        {
            echo "Execute failed: (" . $this->mysqli->errno . ") " . $this->mysqli->error;
            return false;
        }
    }
}

What is happening to me is that whenever I have a duplicate it always enters else , but it prints errno with the correct flag (1062) which is equal to ER_DUP_ENTRY.

My question is Is there a problem to run and only then check to see if it is duplicated and moving forward? Or does the connection close after the error?     

asked by anonymous 06.06.2014 / 16:04

1 answer

2

When errors occur in mysql they trigger a kind of exception, it does not close the connection with mysql, but it interrupts the instruction that is running, however in some cases this behavior can be modified. In procedures, trigger, functions, you can use HANDLER to continue execution even after a error, or use SIGNAL to generate an error in specific cases or even change the mistake. But to treat the duplicate key error during the insert you also have the option to use the INSERT IGNORE or perform the data processing in the INSERT statement itself by instructing mysql to treat the duplicate data using the ON command DUPLICATE KEY UPDATE . Also for fahas handling you can use work with transaction and use commit and rollback.

    
26.06.2014 / 14:14