dallardtech
dallardtech

Reputation: 185

How to duplicate / clone sql records with a diffrent id in PHP?

I have a database structure as follows:

P_Id    content     FirstName   
1       Hansen      Timoteivn 10    
1       Svendson    Tove    
1       Pettersen   Kari 

I would like to be able to duplicate every entry with P_Id as 1 replacing P_id with 2. At the end of the statement I would like to have:

P_Id    content     FirstName   
1       Hansen      Timoteivn 10    
1       Svendson    Tove    
1       Pettersen   Kari 
2       Hansen      Timoteivn 10    
2       Svendson    Tove    
2       Pettersen   Kari 

Any help would be great!

I have an update to my question. What if the table contained multiple entries and I wanted to target specific rows? For instance:

P_Id    content      FirstName   
1       Hansen1      Timoteivn 101    
1       Svendson1    Tove1    
1       Pettersen1   Kari1
2       Hansen2      Timoteivn 102    
2       Svendson2    Tove2    
2       Pettersen2   Kari2
3       Hansen3      Timoteivn 103    
3       Svendson3    Tove3    
3       Pettersen3   Kari3

How would I go about duplicating every P_ID with the value of 2 to P_ID with 4? Resulting in:

P_Id    content     FirstName   
1       Hansen1      Timoteivn 101    
1       Svendson1    Tove1    
1       Pettersen1   Kari1
2       Hansen2      Timoteivn 102    
2       Svendson2    Tove2    
2       Pettersen2   Kari2
3       Hansen3      Timoteivn 103    
3       Svendson3    Tove3    
3       Pettersen3   Kari3
4       Hansen2      Timoteivn 102    
4       Svendson2    Tove2    
4       Pettersen2   Kari2

Thanks guys, this is the final part of the site I am building!

Upvotes: 0

Views: 143

Answers (1)

Timm
Timm

Reputation: 12753

To duplicate all records with a P_Id of 'x' to a P_Id of 'y' (where x and y are numbers) the SQL would be

INSERT INTO yourtable 
    SELECT y AS 'P_Id', content, FirstName 
    FROM yourtable 
    WHERE P_Id = x

remember to replace 'yourtable' with the name of your table!

Upvotes: 3

Related Questions