get the primary key after a DUPLICATE KEY error? - php

If I run an insert query but it fails because of duplicated key error is there any way to get its primary key without doing another select?
Basically:
INSERT INTO tbl (field) VALUES ('myvalue')
This fails because there is already a record with ID:1 and field:myvalue.
Now I Want to know that ID:1 without doing another query:
SELECT id FROM tbl WHERE field = 'myvalue'
is it possibile?

Here is a link that provides four different ways to deal with this:
http://mikefenwick.com/blog/insert-into-database-or-return-id-of-duplicate-row-in-mysql/

There is a provision with each library to get the id of the row which is inserted.
Like: for simple mysql_query() use mysql_insert_id() after that to retrive the id of the last inserted row
Check this link
EDIT:
Please Check that if you have defined the unique index for field column.
If yes then you cannot insert duplicate in the column field

Related

Inserting if not exist or Updating if exist PHP

I want to insert if in the table is not same row with values, but if there is row with the same values I want to only update one that will add +1 to the current value. I have current code, but it doesn't seem to update values in row that exists.
INSERT INTO raport(id, wykonawca, tytul, czas_trwania, powtorzenia)
VALUES('','$wykonawca2','$tytul2','$czas_trwania2', '$powtorzenia2')
ON DUPLICATE KEY UPDATE wykonawca='$wykonawca2', tytul='$tytul2', czas_trwania='$czas_trwania2',
powtorzenia='$powtorzenia2'+1
Ensure your table has a column declared as UNIQUE or PRIMARY KEY and is not an Auto-increment column
If you specify an ON DUPLICATE KEY UPDATE clause and a row to be inserted would cause a duplicate value in a UNIQUE index or PRIMARY KEY, an UPDATE of the old row occurs. For example, if column a is declared as UNIQUE and contains the value 1, the following two statements have similar effect:
INSERT INTO t1 (a,b,c) VALUES (1,2,3)
ON DUPLICATE KEY UPDATE c=c+1;
UPDATE t1 SET c=c+1 WHERE a=1;
(The effects are not identical for an InnoDB table where a is an auto-increment column. With an auto-increment column, an INSERT statement increases the auto-increment value but UPDATE does not.)
MySQL Reference
EDIT :
Your id column is empty you need to pass a value
The actual answer to your initial question as to why the rows do not update is because you are not passing a value for the PRIMARY KEY - this is your AUTO-INCREMENT id column.
Every time you pass :
VALUES('','$wykonawca2','$tytul2','$czas_trwania2', '$powtorzenia2')
this means that your id column is blank, so there is no duplicate just a new row. If you want to have an ON DUPLICATE KEY UPDATE you'll need to pass in the id.
For some more info about ways to handle multiple indexes and DUPLICATE UPDATE check this question out: MySQL behavior of ON DUPLICATE KEY UPDATE for multiple UNIQUE fields
Also, you should read this and action it as soon as possible, you shouldn't be passing variables straight into sql - it's hugely outdated and very unsafe:
How can prepared statements protect from SQL injection attacks?

Insert or Update if duplicate based on unique index

Here is what I want to do. Insert if the unique index (code) doesn't exist in the table already. If it exists then simply update the row.
I can't use primary key because it is Auto Increment ID. Here is the code
$sql="INSERT INTO codes (code,registration,country)
VALUES ('$war','$regi','$country') ON DUPLICATE KEY UPDATE code='$war', registration='$regi', country='$country'";
But it doesn't work because I think it is checking for duplicate primary key. So when I try to insert the row in which the value of column code is same as previous row I get Duplicate entry 'xxx' for key 'code' error. So how to make this work for unique index code ?
Ahmar
ON DUPLICATE KEY UPDATE works with UNIQUE indexes as well as PRIMARY KEY values. Try setting one of the values you are trying to update to be UNIQUE on your database table.
All you have to do is set code to be a unique index. Then, anytime you try to do an insert where code matches it will update instead.
Alter this code as needed
alter table `table` add unique index(`code`);
You are correct, having a primary key on your table will not allow you to insert duplicate key values.
In the past, I have used something like this:
SELECT COUNT(*)
FROM codes
WHERE code = '$war'
Then if the count is > 0, you know there's a duplicate and you do:
UPDATE codes
SET registration = '$regi', country = '$country'
WHERE code = '$war'
Otherwise you do:
INSERT INTO codes (code, registration, country)
VALUES ('$war', '$regi', '$country')
However, if we assume you're using MySQL, you might be able to make use of either INSERT IGNORE or REPLACE.
If you use:
INSERT IGNORE codes (code, registration, country)
VALUES ('$war', '$regi', '$country')
The values will be inserted if the code does not already exist. If the code does exist, no record is inserted and MySQL will silently discard the statement without generating an error.
I think what you probably want is this:
REPLACE INTO codes (code, registration, country)
VALUES ('$war', '$regi', '$country')
REPLACE INTO behaves just like INSERT INTO if the record is new. But if the primary key is duplicated, it will perform an UPDATE instead.
Again, INSERT IGNORE and REPLACE INTO are for MySQL only.
Reference: http://www.tutorialspoint.com/mysql/mysql-handling-duplicates.htm

How to get MySQL value from certain row?

I have a table with 5 rows. Every time a user enters data into a form, it is entered into the table. My first column is called id and holds the number of the post. What I want to do is get the value of id from the previous row, add one to it and set it as the value in the current post's id field. How do I do this?
Just set that field as primary key and auto-increment, it will automatically do this for you. You won't have to fetch the previous row and add that field value to next one.
The SQL query you need is:
SELECT max(id)
FROM tableName;
Set attribute auto increment for "ID" field in the table that contains 5 columns.
You can use sql query like
"INSERT INTO my_table (id auto_increment,primary key(id))";
then you can get...
and eachtime you need not worry to insert id ,it will automatically increments
I would not recomend doing this as it could lead to a race condition.
Change the table structure and set the id field to be the primary key and set it to auto increment. This way anytime a new row is added, it will auto-magically be assigned the next ID.
see this answer on details of how to set auto increment.
here is the query to alter your table and it will set your field or column as primary key and also auto increment it.
ALTER TABLE tbl ADD id INT PRIMARY KEY AUTO_INCREMENT;

Using ON DUPLICATE KEY UPDATE with 2 keys

I have a table with columns id, user_id, post_id, like, views. When a user click the Like button, a row will be added to the table with the corresponding user_id and post_id, and like will be set to 1. If the row already exist and the like column already is 1, nothing will happen.
When the user visits a particular page, a row will be added to the table with the corresponding user_id and post_id, and view will be set to 1. However if the row already exist, the value in view will be incremented.
Problem: I tried using INSERT INTO mytable ... ON DUPLICATE KEY UPDATE like = 1, but the primary key of the table is id and not user_id or post_id. If I set the primary key to either user_id or post_id, there will be a problem because the row will only be duplicated if there exist a row with the same user_id and post_id.
In this situation, how should the query be built?
Or will a better situation be to split the table into 2 tables, one for likes and 1 for views. If this is the case, I still need to make the row unique based on both user_id and post_id columns.
Or do multiple SQL queries?
Please advise, thanks!
I would suggest that you have a table for likes, and then in whatever table that you keep posts in, you add a row for views. So whenever this post is viewed, you simply update the view value for that post to view = view + 1.
Now to address the problem that you outlined about the primary keys, you should note that you can use a unique key in that scenario, which can apply to multiple columns and would fix the issue that you ran into. So for example if in your scenario you had a unique key that encompassed both the userid and postid, your database would not allow for two different rows in that table with the same userid and postid.
So for future reference, use a unique key if you need to :)
discard the id as primary key
use two tables
make primary key on (user_id, post_id)
when handle insert like, do a insert ignore
when handle insert view, do a insert .. duplicate key update view = view+1

MySQL Insert on Duplicate Key

I am building a rating system, and i want to insert a new row, if the name field does not already contain the name i want to insert, and if it does exist, i want to increase the count field by 1
For example, if i have a row the the name 'Tom' and i try to insert another row with the name 'Tom, then i want to +1 for the field count on the row that already exists.
If a row with the name 'Tom' does not exist, i want to insert a new one and set count to 1.
I know i could do this with about 3 SQL statements and some if statements, but that would slow down the script as 2/3 sql commands are being executed.
Any ideas?
Thanks!
see INSERT ... ON DUPLICATE KEY UPDATE
If you specify ON DUPLICATE KEY UPDATE, and a row is inserted that would cause a duplicate value in a UNIQUE index or PRIMARY KEY, an UPDATE of the old row is performed.
e.g.
INSERT INTO table (name,counter) VALUES ('Bob', 1)
ON DUPLICATE KEY UPDATE counter=counter+1

Categories