简体   繁体   中英

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.

My table: 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.

I tried the below loops, but the result is giving the IMG_KEY the value 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.

在此处输入图片说明

Ok, I'm still not 100% sure what you want, but my guess is that you are looking for something like this:

$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.

Since mysql_fetch_assoc($getImages) is a function that loops through all rows in a set of results. So for each iteration of your for loop, it updates all records to have the same $img_key .

Also, really do refrain from using mysql_* functions, they're deprecated. Read this thread: Why shouldn't I use mysql_* functions in PHP?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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