我需要使用位于第二个表格中的新唯一电话号码更新整个列。我似乎走在正确的轨道上......但我的循环逻辑是错误的。
据我所知,我正确地返回了匹配项,但是当我尝试更新表中的整个列时,它会在每一行中插入最后一个电话号码。
$query = "SELECT matched.duns, matched.new_p1, users_data.temp_duns
FROM matched
INNER JOIN users_data ON temp_duns
WHERE temp_duns = duns LIMIT 10";
$result = mysqli_query($connection, $query);
foreach ($result as $key => $val) {
if($val['duns'] === $val['temp_duns']) {
$final_query = "UPDATE users_data SET phone_number = " . $val['new_p1'];
$final_result = mysqli_query($connection, $final_query);
echo $counter . "DUNS From matched: " . $val['duns'] . " DUNS From users_data: " . $val['temp_duns'] . " NEW PHONE: ". $val['new_p1']. "<br>";
}
}
我是新手,但任何帮助都会受到赞赏。
答案 0 :(得分:0)
问题是您的查询没有WHERE
子句,因此它会更新每一行。
"UPDATE users_data SET phone_number = " . $val['new_p1'];
您需要将其限制为您要更新的行。
"UPDATE users_data SET phone_number = " . $val['new_p1'] . " WHERE some_id = " . $some_id;
你可以在一个查询中完成整个事情。
UPDATE table_to_be_updated
JOIN table_with_value_we_need ON whatever_joins_them
SET table_to_be_updated.column_we_want_to_fill = table_with_value_we_need.value_we_need;
答案 1 :(得分:0)
只需在一次调用中运行更新查询而无需循环,可以使用MySQL INNER JOIN
:
UPDATE user_data u
INNER JOIN matched m ON u.temp_duns = m.temp_duns
SET u.phone_number = m.new_p1;
或者限制为10:
UPDATE user_data u
INNER JOIN (SELECT * FROM matched LIMIT 10) m ON u.temp_duns = m.temp_duns
SET u.phone_number = m.new_p1;