我对向 mysql 和 PHP 编写查询还是新手,所以我确信这是一个新手错误,但我无法弄清楚。
当我用 Echo 显示变量时,这些变量显示为不同的值,但当我尝试更新时,它只更新一行。
出现错误后:- 键“PRIMARY”的重复条目“654-657”
我在 While 循环方面遇到问题,但不知道在哪里
任何帮助将不胜感激。
<?php
$index = 0;
while($row = mysql_fetch_array($find))
{
//Take Row Value with , from "Ratings" tables and Store In Variable
$rating_exp = $row['ratings'];
echo "<br />Orignal Rating = $rating_exp<br />";
// Use EXPLODE function to store String Value In ARRAY Very Most IMP Step.
$rating_exp = explode(',', $rating_exp);
//Take First element of the arrray And Store In Variable.
$First_element_array = array_shift(array_values($rating_exp));
//Make array values = First element value Untill Array = 4.
$sum = 0; //Declare Variable to Store SUM value.
for($i = 0; $i<4 ; $i++)
{
//Create Array With First Element Value For 4 step.
//Store in Array
$rating_exp[$i] = $First_element_array;
$sum+=$First_element_array;
}
//Convert Array to the String With , Use Function implode.
$string = implode(',', $rating_exp);
echo "<br />---------------------------------<br />";
//Store Values in Database For Update Rating Table
$update_rating_id = $row['rating_id'];
$update_reviewid = $row['reviewid'];
$update_ratings = $string;
$update_ratings_sum = $sum;
$update_ratings_qty = 4;
echo "update_rating_id $update_rating_id <br />";
echo "update_reviewid $update_reviewid <br />";
echo "update_ratings $update_ratings <br />";
echo "update_ratings_sum $update_ratings_sum <br />";
echo "update_ratings_qty $update_ratings_qty <br />";
echo "<br />---------------------------------<br />";
echo "---------------------------------<br />";
$Update_Rating = "UPDATE Ratings R JOIN Comment C ON C.id = R.reviewid SET R.rating_id = '$update_rating_id',R.reviewid='$update_reviewid', R.ratings='$update_ratings', R.ratings_sum ='$sum',R.ratings_qty='$update_ratings_qty' where C.pid = 763";
$Update_Rating1 = mysql_query($Update_Rating);
if (!$Update_Rating1) die("Query failed: $Update_Rating\n" . mysql_error());
$index++;
}
echo "<br /><br />Total Updated Records = $index<br />";
?>
最佳答案
每次只更新一行,因为 Update 语句有 where C.pid = 763
这应该类似于 where C.pid = $pid
吗?
此外,您的 $string = implode(',', $ rating_exp);
始终会在数组中包含 4 个第一项。 for 循环之前将“First_element_array”分配给数组中的前 4 个槽,然后将其转换为字符串。
--- 评论中解决方案的更新:
更新查询匹配多个要更新的行,但是 ratings_id 是主键。因此,它将成功更新第一行,然后在第二行上失败,因为它将尝试更新主键以具有我们刚刚在第一行中设置的相同值。
关于php - 仅更新 1 行 While 循环错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17052078/