Answer the question
In order to leave comments, you need to log in
How to increment if there is a unique field?
There is a page(id, url) table. I write to the database from an array, where the elements themselves are unique, but they may not be unique relative to the database. In the database, the url field is unique. But making the following request
$sql = "INSERT IGNORE page (id, url, title) VALUES ";
foreach ($links as $value) {
$sql .= "(".$id.", '".$value[0]."', '".addslashes($value[1])."'), ";
++$id;
}
$sql = rtrim($sql, ", ");
it increments the counter even when it hasn't added an element. How it is possible to correct it?
Answer the question
In order to leave comments, you need to log in
The first huge problem is that you are building a query by concatenation, which means you are exposing yourself to the risk of SQL injection. Use PDO .
The second huge problem is that you impudently ignore the errors that occur when inserting, as a result, your key number grows. Because the database first creates a new number, then tries to insert, gets an error and moves on.
If you are so interested in not leaking numbers (although this is not true from an architectural point of view), you will have to check (with a serious performance penalty) before inserting each row for its presence in the database.
If you decide to simply decrement the counter when an error occurs while trying to insert a double, you will make a mistake, as you can ruin this very counter by creating a race.
The first thing to know - WHY do you need this - "do auto-increment only when it actually added a record"? What do you care what value this field has?
Answer in detail
1) For addslashes() instead of mysql_real_escape_string() you need to twist your hands
2) What is $id? Use auto-increment in the table at the database level, the database will increase it itself when inserting
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question