Search code examples
phpmysqlarray-intersect

Copy data from one MySQL table to another when data intersect using PHP


I'm new to programming and would really appreciate your help. :) So, I have a USER table and a SALES table. On the SALES table I only have name and last name of the users. On the USER table I have name, last name, USER_ID, email and etc...

I need to copy the USER_ID from the USER table to the SALES table when NAME and LAST NAME are a match.

Here is the structure:

USER_TABLE_A
USER_ID_A
NAME_LASTNAME_A

SALES_TABLE_B
ROW_ID_B
NAME_B
LASTNAME_B
USER_ID_B (empty)

So far I got both tables to show data when they intersect but have no idea where to go from here. Could anyone please help?

    $sql1 = mysql_query("SELECT name_B, lastname_B, user_id_B, row_id_B FROM sales_table_B WHERE name_B IS NOT NULL AND lastname_B IS NOT NULL", $db);
    $sql2 = mysql_query("SELECT name_lastname_A, user_id_A FROM user_table_A WHERE name_lastname_A IS NOT NULL", $db);
    $a1 = array();
while ($row = mysql_fetch_array($sql1)) {
    $id = $row['row_id_B'];
    $name1.$id = $row['name_B']." ".$row['lastname_B'];
    array_push($a1, $name1.$id);
}
    $a2 = array();
while ($row2 = mysql_fetch_array($sql2)) {
    $id2 = $row2['user_id_A'];
    $name2.$id2 = $row2['name_lastname_A'];
    array_push($a2, $name2.$id2);
} 
    $result = array_intersect($a1,$a2);
    print_r($result);

Thanks in Advance!


Solution

  • Thank you so much Darshan!! Your answer was missing a ) after limit 1 but with the adjustment it worked beautifully! Here is the code that worked:

    UPDATE sales_table_b
    SET user_id_b = (SELECT user_table_a.user_id_a
                     FROM user_table_a
                     WHERE user_table_a.name_lastname_a = CONCAT(sales_table_b.name_b, ' ' , sales_table_b.lastname_b) LIMIT 1)
    WHERE EXISTS (SELECT *
              FROM user_table_a
              WHERE user_table_a.name_lastname_a = CONCAT(sales_table_b.name_b, ' ' , sales_table_b.lastname_b))