Question

So in this piece of code, I just deleted a row from the table, and so, the values for img_pos were: 1,2,3,4,5 And now, they are (assuming we deleted the third entry): 1,2,4,5 Of course, I want this to be: 1,2,3,4

So I have to batch rename the rows.

I got this, but doesn't seem to work....

$sql = "SELECT * FROM $tableImg WHERE img_acc = $accid ORDER BY img_pos";
$res = mysql_query($sql);
$num = mysql_num_rows($res);

$i = 0;
$n = 1;
while($i<$num){
    $sql = "SELECT * FROM $tableImg WHERE img_acc = $accid ORDER BY img_pos DESC LIMIT $i,1";
    $res = mysql_query($sql);
    $row = mysql_fetch_array($res);
    $img_pos = $row['img_pos'];

    $sql = "UPDATE $tableImg SET img_pos = '$n' WHERE img_acc = '$accid' AND img_pos = '$img_pos'";
    $res = mysql_query($sql);
    $i++;
    $n++;
}
mysql_close();

$tableImg is just a variable containing the table name, that works just fine. I guessthe problem is somewhere around "$img_pos = $row['img_pos'];", because all the querys are used somewhere differently, be it slightly different, and they should work...

Thanks in advance!

Was it helpful?

Solution

I ended up simply doing this:

$i = 1; 
while($row = mysql_fetch_array($res)){
    $old_pos = $row['img_pos'];
    $sql = "UPDATE $tableImg SET img_pos = $i WHERE img_acc = $accid AND img_pos = $old_pos";
    $res = mysql_query($sql);
    $i++;
};

OTHER TIPS

This is quite possible, just totally unnecessary. The nice thing about digital data is that you don't have to look at it so it doesn't matter if it's a bit gappy, does it?

If you REALLY want to do this (say, you are building an application and you are just cleaning up the stuff you deleted whilst working on it) the following example will do in in SQL, as this simple example shows:

CREATE TABLE disorder (id int,stuff CHAR(6));
CREATE TABLE disorder2 (id SERIAL,stuff CHAR(6));
INSERT INTO disorder (id,stuff)
VALUES
('1','ONE'),
('2','TWO'),
('3','THREE'),
('4','FOUR'),
('5','FIVE');
DELETE FROM disorder WHERE id='3';


INSERT INTO disorder2 (stuff) SELECT stuff FROM disorder;
TRUNCATE TABLE disorder;
INSERT INTO disorder SELECT * from disorder2;
DROP TABLE disorder2;

This can be seen in action on sqlfiddle but it's pretty obvious. If you do a SELECT * from disorder, you will see why you probably shouldn't do this sort of thing.

Your tables really do need to have primary keys. This speeds searches/indexing and makes them useful. Look up database normal forms for a thorough discussion of the reasoning.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top