Search code examples
phpmysqlprimary-keyresetrebuild

PHP/MySQL: Rebuild primary key field


Problem:

Primary key field is 'ID'

Data is inserted/updated into it using a REPLACE INTO command, which is easy to use but unfortunately increases the 'ID' value of the Record it is replacing.

So I need a way to completely rebuild the ID feild so that:

| ID  |  Name   |
|===============
| 21  |  deer   |
| 8   |  snow   |
| 3   |  tracks |
| 14  |  arrow  |

Goes to:

| ID |  Name   |
|===============
| 1  |  deer   |
| 2  |  snow   |
| 3  |  tracks |
| 4  |  arrow  |

and I need to do it through php.

Current Attempts:

<?php
$reset = "SET @num := 0;
UPDATE `users` SET `ID` = @num := (@num+1);
ALTER TABLE `users` AUTO_INCREMENT =1;";

$con = mysql_connect("mysql2.000webhost.com","db_user","password");  
if (!$con)
{
     die('Could not connect: ' . mysql_error());
}
mysql_select_db("db_name", $con);
if (!mysql_query($reset,$con)) 
  {
    die('<h1>Nope:</h1>' . mysql_error());
  }
mysql_close($con);
?>

and trying:

$reset = "ALTER TABLE `users` DROP `ID`;
ALTER TABLE `users` AUTO_INCREMENT = 1;
ALTER TABLE `users` ADD `ID` int UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY FIRST;`";

also yielded no results.

Strangness of it all

Both the $reset commands I tried both execute perfectly in MySQL, but for some reason they fail to act properly from PHP.


Answer

As pointed out the answer, @ variables are preserved per connection, so it is perfectly reasonable to run multiple queries:

///Trigger multiple queries
$nope = '<h1>Nope:</h1>  ';
$res1 = "SET @num := 0;";
$res2 = "UPDATE `users` SET `ID` = @num := (@num+1);";
$res3 = "ALTER TABLE `users` AUTO_INCREMENT =1;";
if (!mysql_query($res1,$con)) die($nope . mysql_error());
if (!mysql_query($res2,$con)) die($nope . mysql_error());
if (!mysql_query($res3,$con)) die($nope . mysql_error());
mysql_close($con);

Solution

  • mysql_* does not support running multiple queries. You have to run them separately