Reputation: 390
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.
Upvotes: 0
Views: 436
Reputation: 1293
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?
Upvotes: 1