2014-02-07 84 views
1

我正在使用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.'"); 
} 
?> 
+0

我的回答有帮助吗? –

回答

1

更新的顺序应该是这个样子,只是使用的5一ID为修改后的项目和2个新的单编号,为举例起见的查询:

UPDATE table SET orderID=2 WHERE ID=5; 

UPDATE table SET orderID=orderID+1 WHERE ID!=5 AND orderID >= 2; 

对不起,我没有时间专门为您的表设置,但这应该让你在正确的轨道上。

+0

我想先将列添加到我的表中。我目前只有一个ID列。我的桌子上没有订单栏。我在问如何将订单列添加到表中。不过谢谢你。 – Kelsey