I have a database which must maintain a strict primary key numerical sequence in its id
column. i.e. 1, 2, 3, 4, 5, etc.
Now when I delete a row I then need to do a recount and an increment reset using:
SET @count = 0;
UPDATE `Main`
SET `id` = @count:= @count + 1;
ALTER TABLE Main
AUTO_INCREMENT =1;
This works fine when typed into the MySQL command line and is exactly what I want however I need to execute it from a PHP script command. I use:
$sql="SET @count = 0";
$result=$database->query($sql);
$sql="UPDATE Main SET id = @count:= @count + 1";
$result=$database->query($sql);
$sql="ALTER TABLE Main AUTO_INCREMENT =1";
$result=$database->query($sql);
Now the first two recount lines work fine but the AUTO_INCREMENT
line will not reset the auto increment counter. Again "ALTER TABLE Main AUTO_INCREMENT =1;"
works fine directly from the MySQL command line but not when executed through the PHP script.
Note: the database uses the mysqli_query
command.