简体   繁体   English

用增量值更新表

[英]Update table with increment value

Im trying to update a value in a table, using while loop, but i want this value to be like using auto_inc key. 我试图使用while循环更新表中的值,但我希望此值像使用auto_inc键一样。

My table: ID / CAR_ID / IMG_KEY / IMAGE 我的表格: ID / CAR_ID / IMG_KEY / IMAGE

i want to take 12 rows of the same CAR_ID and give the IMG_KEY values from 1-12. 我想使用12行相同的CAR_ID并提供1-12之间的IMG_KEY值。

I tried the below loops, but the result is giving the IMG_KEY the value 1 我尝试了以下循环,但结果是给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());
        }
    }

The goal is give to the following 12 rows img_key values from 1 to 12 and all the other values as they are. 目标是给以下12行img_key值(从1到12)以及所有其他值。

在此处输入图片说明

Ok, I'm still not 100% sure what you want, but my guess is that you are looking for something like this: 好的,我仍然不能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());
}

In your question, your for loop isn't doing anything other than looping, in your case it iterates twelve times. 在您的问题中,您的for循环除了循环外没有做任何其他事情,在您的情况下,它会迭代十二次。

Since mysql_fetch_assoc($getImages) is a function that loops through all rows in a set of results. 由于mysql_fetch_assoc($getImages)是一个遍历一组结果中所有行的函数。 So for each iteration of your for loop, it updates all records to have the same $img_key . 因此,对于for循环的每次迭代,它会将所有记录更新为具有相同的$img_key

Also, really do refrain from using mysql_* functions, they're deprecated. 另外,确实不要使用mysql_*函数,因为它们已被弃用。 Read this thread: Why shouldn't I use mysql_* functions in PHP? 阅读此线程: 为什么我不应该在PHP中使用mysql_ *函数?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM