Insert the last table data into a second table

Asked

Viewed 166 times

2

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

I TRIED THAT, BUT HE ONLY INSERTS 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 go to the head together"

  • If you need to keep the two tables identical, it would not be better to use a Trigger within the database?

2 answers

3


If the ids have the same value in both tables ex id 1 - café. Can make the difference of product table 1 by product 2 and use 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)
  • PERFECT! It worked :0

0

This instruction only entered the last one, because it is using LIMIT 1, if you know how many records you need to copy change the LIMIT. Give more details about the process, this routine is part of an external verification of the registration operation, or it needs to be in real time as a mirror table?

For the second case, a good feature would be the use of triggers (triggers), as vc can easily mount an "Insert Into Select" command and Mysql is free to fire Rigger whenever necessary.

Ref.: http://dev.mysql.com/doc/refman/5.0/en/create-trigger.html

I hope I’ve helped, if I have to set an example for you

  • #Jotasantana, my big one. Thanks for wanting to help. Come on... It’s a JSON request from a mobile device. In fact the product_1 is a String parameter that comes from a Java function stored via POST, so it would spin > if (! $db->Query("SELECT * FROM {$_POST['emails']} ORDER BY id ASC LIMIT 1")) $db->Kill(); while (! $db->Endofseek()) { $Row = $db->Row(); $idPost= $Row->id; } mysql_query("INSERT INSERT {$_POST['emails']} SELECT * FROM post WHERE id > '.$idPost.'");

  • When I set a higher limit, it scans the ID of the column corresponding to the order. LIMIT 1, last id 15 in echo. LIMIT 5, 10th ID in echo. This I do not understand. It presents only one value!

  • It’s an outside operation.

  • From the code you posted, I believe that the "Insert" has to be inside the loop, as it is after the variable ends up with the last id of the list (using Limit 5)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.