[英]Using foreach loop to update MySQL table with array of IDs
I'm trying to update a MySQL table with three columns (id, franchise_id, state_id) with data from an array by using a foreach loop. 我正在尝试通过使用foreach循环使用数组中的数据更新具有三列(id,franchise_id,state_id)的MySQL表。 The table updates but the four rows that match the franchise_id are being updated with the last item in the array (4).
该表将更新,但是与franchise_id匹配的四行将使用数组(4)中的最后一项进行更新。 I can't figure out where the error is.
我不知道错误在哪里。
Data passed to the function: 数据传递给函数:
$states = [1,2,3,4];
$franchise_id = 5;
The update function: 更新功能:
public static function update($franchise_id, $states)
{
try
{
// establish db connection
$db = static::getDB();
$sql = "UPDATE franchise_states SET state_id = ? WHERE franchise_id = ?";
$stmt = $db->prepare($sql);
foreach($states as $state)
{
$stmt->execute([$state, $franchise_id]);
}
return $stmt;
}
catch (PDOException $e)
{
echo "Error updating franchise data: " . $e->getMessage();
exit();
}
}
I appreciate any help. 感谢您的帮助。
Thanks! 谢谢!
Actually it's updating for all the values in $states array but the last one stays because, well, it is the last executed one. 实际上,它正在为$ states数组中的所有值进行更新,但最后一个保留了,因为它是最后执行的一个。
You try to update state_id against the same value franchise_id=5
and since all of them has the same franchise id, the last value stays. 您尝试针对相同的值
franchise_id=5
更新state_id,并且由于它们都具有相同的特权ID,因此最后一个值保持不变。
Have you try to edit this line? 您是否尝试编辑此行?
foreach($states as $state)
to 至
foreach($state as $states)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.