![](/img/trans.png)
[英]How to link the foreign key field to a primary key field from another table using php and mysql?
[英]PHP/MySQL: Rebuild primary key field
主鍵字段為'ID'
使用REPLACE INTO
命令將數據插入/更新到該命令中,該命令易於使用,但遺憾的是增加了它正在替換的Record的'ID'
值。
所以我需要一種方法來完全重建ID
字段,以便:
| ID | Name |
|===============
| 21 | deer |
| 8 | snow |
| 3 | tracks |
| 14 | arrow |
去:
| ID | Name |
|===============
| 1 | deer |
| 2 | snow |
| 3 | tracks |
| 4 | arrow |
我需要通過PHP來做到這一點。
<?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);
?>
並嘗試:
$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;`";
也沒有結果。
我試過的$reset
命令都在MySQL中完美執行,但由於某些原因它們無法從PHP中正常運行。
正如答案所指出的,每個連接都保留@變量,因此運行多個查詢是完全合理的:
///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);
mysql_*
不支持運行多個查詢。 你必須單獨運行它們
INSERT INTO ... ON DUPLICATE KEY UPDATE ...
,您可以保留您的'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);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.