Is it possible to run a query (Insert) and only then check if it is duplicated?

Asked

Viewed 354 times

5

I am reading an XML file and at the same time insert the entries in the BD.

My code is 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’s happening to me is that every time I have a duplicate, it always goes into else, but prints Errno with the correct flag (1062) which is equal to ER_DUP_ENTRY.

My question is there is problem to run and only then check if it is duplicated and advance? Or the connection closes after the error?

  • You use storade Procedure?

  • For security work with Primary Keys or Unique Keys.

  • @abfurlan no, it’s direct even.

  • @Motta and work, that’s the case, gives duplicate key BD error...

  • @Jorge B. , the idea is this, make a mistake.

  • @Motta I know, but read my question in bold, does the connection close after the error? Is that I have no idea why but this code if ( $this->mysqli->errno == ER_DUP_ENTRY ) is always false even if Errno = 1062, and I have no idea why...

  • @Jorge B. I can’t say.

  • 1

    Before the if comparison makes var_dump($this->mysqli->errno); to see the type/value you are receiving... may give you some insight into the problem. The same applies to ER_DUP_ENTRY.

  • @Zuul They’re both of the same value.

Show 4 more comments

1 answer

2


When errors occur in mysql they trigger a kind of exception, do not close the connection to mysql, but interrupt the instruction that is running, however in some cases this behavior can be modified. In procedures, Trigger, functions can be used HANDLER to continue execution even after an error, or to use the SIGNAL to generate an error in specific cases or even change the error. But to handle duplicate key error during Insert you also have the option to use the INSERT IGNORE or perform data processing in the INSERT instruction itself by teaching mysql to handle duplicated data through the ON command DUPLICATE KEY UPDATE. Still for fahas treatment you can use work with transaction and use commit and rollback.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.