我正在使用PHP,我想用行Orderid,ID,Employee_Name和Employee_Salary生成一個表。我想要兩個ID列,因爲我試圖讓用戶能夠向上或向下移動表格行來更改表格行的順序。顯然,從我讀過的內容來看,唯一的方法是通過擁有一個ID列和一個Order ID列來操縱表格行的順序。如何使用PHP在MySQL表中插入訂單ID列和ID列?
這是我想用來上下移動行的代碼。例如,我希望用戶能夠單擊向上箭頭按鈕將第1行:Kelsey,第2行:Max,第1行:Max,第2行:Kelsey更改爲行。
PHP代碼:
<?php
// Variables -- Fill these out from the results of your page. (i.e. what item id to move up or down)
$id_item = 1; // ID of item you want to move up/down
$isUp = true; // Change to false if you want to move item down
// MySQL structure -- Fill these out to execute your queries without needing to update my code
$table_name = "employee"; // Name of table with your items in it
$col_position = "position"; // Name of column with position ID (Remember, this must be UNIQUE to all items)
$col_id = ""; // Name of column containing the items id (most likely the auto_incremented column)
if ($isUp)
{
$operator = "<";
$order = "DESC";
}
else
{
$operator = ">";
$order = "ASC";
}
// Get row we are moving
$request = mysql_query("
SELECT '.$col_position.', '.$col_id.' FROM '.$table_name.'
WHERE '.$col_id.' = '.$id_item.'
LIMIT 1");
// Save data for row we are moving
if(mysql_num_rows($request) > 0) {
$isPos1 = true;
while($row = mysql_fetch_assoc($request)) {
$position1 = $row[$col_position];
$id_item1 = $row[$col_id];
}
}
// Get row we want to swap with
$request2 = mysql_query("
SELECT '.$col_position.', '.$col_id.' FROM '.$table_name.'
WHERE '.$col_position.' '.$operator.' '.$position1.'
ORDER BY '.$col_position.' '.$order.' LIMIT 1");
// Save data from row we want to swap with
if(mysql_num_rows($request2) > 0) {
$isPos2 = true;
while($row = mysql_fetch_assoc($request2)) {
$position2 = $row[$col_position];
$id_item2 = $row[$col_id];
}
}
// If both rows exist (indicating not top or bottom row), continue
if ($isPos1 && $isPos2)
{
$query_update = mysql_query("
UPDATE '.$table_name.'
SET '.$col_position.' = '.$position2.'
WHERE '.$col_id.' = '.$id_item1.'");
$query_update2 = mysql_query("
UPDATE '.$table_name.'
SET '.$col_position.' = '.$position1.'
WHERE '.$col_id.' = '.$id_item2.'");
}
?>
我的回答有幫助嗎? –