![](/img/trans.png)
[英]Update single column of table and value should start from 0 and then should increment by 1
[英]Update table with increment value
我試圖使用while循環更新表中的值,但我希望此值像使用auto_inc鍵一樣。
我的表格: ID / CAR_ID / IMG_KEY / IMAGE
我想使用12行相同的CAR_ID
並提供1-12之間的IMG_KEY
值。
我嘗試了以下循環,但結果是給IMG_KEY賦予值1
$getImages = mysql_query("SELECT * FROM more_images WHERE car_id = '$car_id'") or die(mysql_error());
$img_key = 0;
for ($img_key = 1; $img_key <= mysql_num_rows($getImages); $img_key ++) {
while ($selectedImages = mysql_fetch_assoc($getImages)) {
$update = mysql_query("UPDATE `more_images` SET `img_key` = '$img_key' WHERE `car_id` = '$car_id'") or die(mysql_error());
}
}
目標是給以下12行img_key
值(從1到12)以及所有其他值。
好的,我仍然不能100%地確定您想要什么,但是我的猜測是您正在尋找這樣的東西:
$imgKey = 0;
while ($selectedImages = mysql_fetch_assoc($getImages))
{
$imgKey++;
$update = mysql_query("UPDATE `more_images` SET `img_key` = '{$imgKey}' WHERE `car_id` = '{$car_id}'") or die(mysql_error());
}
在您的問題中,您的for
循環除了循環外沒有做任何其他事情,在您的情況下,它會迭代十二次。
由於mysql_fetch_assoc($getImages)
是一個遍歷一組結果中所有行的函數。 因此,對於for
循環的每次迭代,它會將所有記錄更新為具有相同的$img_key
。
另外,確實不要使用mysql_*
函數,因為它們已被棄用。 閱讀此線程: 為什么我不應該在PHP中使用mysql_ *函數?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.