Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

copy and insert row in same table with new primary key+php

my project: PHP

i have a table. i want copy one row into same table with diffrent primary key.

sql code: INSERT INTO messages SELECT * FROM messages WHERE id=’$id’

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

when i click on submit show :
Error: INSERT INTO messages SELECT * FROM messages WHERE id=’12’ Duplicate entry ’12’ for key ‘PRIMARY’

>Solution :

Because you’re trying to insert every field in that row, which includes the primary key. If you want to specify a subset of fields, specify a subset of fields:

INSERT INTO messages (ColumnA, ColumnB, Etc)
SELECT ColumnA, ColumnB, Etc
FROM messages WHERE id='$id'

That way you’re not also inserting a value into id.

(This is of course assuming that the database auto-generates the primary key. If it doesn’t, you’d need to insert whatever value would be required for a primary key.)


As an aside, the use of what appears to be a PHP variable (and explicit quotes) in your SQL code strongly implies that you are likely vulnerable to SQL injection. Right now is the best time to correct that.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading