Insert the last data of a table into a second table

2

I have a problem with INSERT in PHP. I have a table named products_1 and another called products_2. Table 1 has the same products as the second, but with 5 more products, ie ID 11, 12, 13, 14 and 15 are not inserted in products_2. I need to "copy", insert this 5 products, at a time, into the products_2. And every time there are more products in the products_1 table.

I TRIED THAT, BUT HE INSERT ONLY ID 15, THE LAST>

if (!$db->Query("SELECT * FROM produtos_2 ORDER BY id DESC LIMIT 1")) 
    $db->Kill();

while (! $db->EndOfSeek()) {
    $row = $db->Row(); 
    $idprodutos2= $row->id;
}
mysql_query("INSERT INTO produtos_2 SELECT * FROM produtos_1 WHERE id > '.$idprodutos2.'");

"Let's get together"

    
asked by anonymous 08.12.2014 / 14:57

2 answers

3

If the ids have the same value in both tables ex id 1 - coffee. You can make the difference from table product1 by product2 and use the result as insert at once.

Insert into produto2(id, descricao)    
select id, descricao from produto1 
where not exists ( select id from produto2 where id = produto1.id)
    
08.12.2014 / 16:07
0

This statement only inserted the last, since you are using LIMIT 1, if you know how many records you need to copy, change the LIMIT. Give more details about the process, is this routine part of an external verification of the registration operation, or does it have to be real-time as a mirrored table?

For the second case, a good feature would be the use of triggers, since you can easily mount an "Insert Into Select" command and MySQL does not need to trigger the trigger when necessary.

Ref: link

I hope I have helped if I need to put an example to you

    
08.12.2014 / 15:09