今天做系统要用到“上移”或“下移”功能,网上找到下面的方法,虽然繁琐,但是实现起来还算简单。
1、我们数据库表中需要一个排列字段作为移动排序的参考,表中添加字段weight;
2、我们一开始先让weight与ID对应起来,也就是每条记录的ID值:
weight字段设置的和自增字段相同。插入记录后$weight=mysql_insert_id(),得到最近插入记录ID的值,然后更新表:
$sql="update table set weight={$weight} where ID={$ID}";
mysql_query($sql);
移或下移时:取欲移动的新闻的上一新闻或是下一新闻的weight值,然后将自己的weight值改为刚才取出的weight,刚才取出的改为自己的。(交换一下weight值)SQL排序规则:在原有规则(order by)前加入weight desc
-
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
-
<html xmlns="http://www.w3.org/1999/xhtml">
-
<head>
-
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
-
<title>实现新闻的上移下移功能</title>
-
</head>
-
-
<body>
-
<style>
-
*{font-size:12px;}
-
td{height:24px; line-height:24px; text-align:center}
-
</style>
-
-
<?php
-
header("Content-type:text/html;charset=gb2312");
-
include("mysql.class.php");
-
$conn=new mysql("localhost","root","root","test"," ","gbk");
-
if(!emptyempty($_GET["weight"])){
-
if($_GET["move"]=="up"){
-
-
$query=$conn->query("select * from `article` where `weight` > '$_GET[weight]' order by `weight` asc limit 1");
-
if($conn->db_num_rows(query)>0){
-
$rows=$conn->fetch_array($query);
-
$conn->query("update `article` set `weight`='$rows[weight]' where `weight`='$_GET[weight]'");
-
$conn->query("update `article` set `weight`='$_GET[weight]' where `ID`='$rows[ID]'");
-
}else{
-
echo "<script>alert('已经在最顶上');</script>";
-
}
-
}else if($_GET["move"]=="down"){
-
-
$query=$conn->query("select * from `article` where `weight` < '$_GET[weight]' order by `weight` desc limit 1");
-
if($conn->db_num_rows(query)>0){
-
$rows=$conn->fetch_array($query);
-
$conn->query("update `article` set `weight`='$rows[weight]' where `weight`='$_GET[weight]'");
-
$conn->query("update `article` set `weight`='$_GET[weight]' where `ID`='$rows[ID]'");
-
}else{
-
echo "<script>alert('已经在最底下');</script>";
-
}
-
}
-
}
-
?>
-
<table border="1" cellpadding="0" cellspacing="0" width="300" align="center">
-
<caption>文章上下移动</caption>
-
<tr>
-
<td>ID</td><td>标题</td><td>移动</td>
-
</tr>
-
<?php
-
$query=$conn->query("select * from `article` order by `weight` desc");
-
if($conn->db_num_rows($query)>0){
-
while($rows=$conn->fetch_array($query)){
-
$aid[].=$rows["ID"];
-
?>
-
<tr>
-
<td><?php echo $rows["ID"]?></td>
-
<td><?php echo $rows["title"]?></td>
-
<td><a href="<?php $PHP_SELF?>?weight=<?php echo $rows[weight]?>&move=up">上移</a>/<a href="<?php $PHP_SELF?>?weight=<?php echo $rows[weight]?>&move=down">下移</a></td>
-
</tr>
-
-
<?php
-
}
-
}
-
?>
-
</table>
-
</body>
-
</html>
|