Reputation: 85
I am using the code below to input transactions into a database. Each transaction has a unique "id" associated with it, so in phpMyAdmin, I declared the "id" field (actually called transaction_id in my database) to be a unique value, thus preventing duplicates. Now when I download the transaction data into the database, it only adds in new transactions.
This causes a large amount of duplicate errors:
*Error: INSERT INTO Transactions (id, transaction_id ... Duplicate entry '#############' for key 'transaction_id'*
I'd like to show all errors except the duplicate error. Is there a way to simply add this with an else if or into the else statement below?
if (mysqli_query($conn, $sql)) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
Upvotes: 0
Views: 1612
Reputation: 8706
Depending on what you want to do with the duplicate, you could just use a select query to check for existence and then not perform the insert.
Alternatively, there is http://dev.mysql.com/doc/refman/5.7/en/insert-on-duplicate.html
The insert on duplicate clause allows you to update a record if it exists, but insert if it doesn't.
Obligatory note: stop using mysqli and start using pdo
Upvotes: 0
Reputation: 85
Thanks guys. Here's what I came up with:
if (mysqli_query($conn, $sql)) {
echo "New record created successfully";
} else if(mysqli_errno($conn) !== 1062) {
echo "Error: " . $sql . "<br>" . mysqli_error($conn); }
Upvotes: 1
Reputation: 2213
Jepf:
You can use the mysqli-error function, in order to retrieve the error code: http://php.net/manual/en/mysqli.error.php
Afterwards, if the error code is 1586, you could add a condition if the error code matches this value.
Here you have the the reference for Mysql error messages: http://dev.mysql.com/doc/refman/5.7/en/error-messages-server.html
Upvotes: -1