Question

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);
Was it helpful?

Solution

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

OTHER TIPS

  1. if you use INSERT INTO ... ON DUPLICATE KEY UPDATE ..., you can keep your 'ID'
function table2array ($table_name, $unique_col = 'id')
    {
$tmp=mysql_query("SELECT * FROM $table_name"); $count = mysql_num_rows($tmp);
while($rows[] = mysql_fetch_assoc($tmp));
array_pop($rows);
for ($c=0; $c < $count; $c++) 
{
  $array[$rows[$c][$unique_col]] = $rows[$c];
}
return $array;
    }

function reindexTable($table_name,$startFrom = 1) // simply call this function where you need a table to be reindexed!
    {
$array = table2array($table_name);
$id = 1; foreach ($array as $row) 
{
mysql_query("UPDATE `".$table_name."` SET `id` = '".$id."' WHERE `".$table_name."`.`id` = ".$row['id']);
$id++;
}
mysql_query("ALTER TABLE  `".$table_name."` AUTO_INCREMENT = ".$id);
    }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top