php与数据库连接如何实现数据的顺序和倒序
这边,我简单用到了一个a标签用来传入order中的值,将order中的值传到地址栏中
当点击倒序或者升序时将order值赋给在php代码中定义的order,然后修改sql语句就可以了
详细代码展示:
<?php
if(isset($_GET['order'])) //判断order中是否有值
{
$order=$_GET['order']; //如果有值就将当前的值赋给变量$order
}
else
{
$order="";
}
$link=mysqli_connect("localhost","root","root"); //链接数据库
mysqli_select_db($link,"test");
mysqli_query($link,"set names 'utf8'"); //设置字符集
$str = "select * from stu order by Id"." ".$order;
$result = mysqli_query($link,$str);
$arr = array();
while($row = mysqli_fetch_array($result)) {
$arr[]=$row;
}
mysqli_close($link);
?>
<!DOCTYPE html>
<html>
<head>
<title></title>
<style>
table,td
{
border: 1px solid #000;
}
</style>
</head>
<body>
<table cellpadding="1" spacpadding="1">
<tr>
<th>id</th>
<th>姓名</th>
<th>年龄</th>
<th>专业</th>
<th>班级</th>
</tr>
<?php
foreach ($arr as $key => $value)
{
?>
<tr>
<td><?php echo $value[0];?></td>
<td><?php echo $value[1];?></td>
<td><?php echo $value[2];?></td>
<td><?php echo $value[3];?></td>
<td><?php echo $value[4];?></td>
</tr>
<?php }?>
</table>
<a href="?order=desc">倒序</a>
<a href="?order=asc">升序</a>
</body>
</html>
进一步思考,如何实现一个a标签实现以上两种方法切换
思路:1.我可以先给a标签加上一个序列,因为当数据显示的时候默认的时顺序排序,我们可以将其设定一个按照倒序排列的情况
2.当我们点击的时候,order的值就变换成倒序(desc),就这样不断的给变量order赋值,他将在desc和asc中不断地切换。
具体实现:
<?php
$order="desc";
if(isset($_GET['order']))
{
$order=$_GET['order'];
if($order=="desc")
$order="asc";
else
{
$order="desc";
}
}
$link=mysqli_connect("localhost","root","root"); //链接数据库
mysqli_select_db($link,"test");
mysqli_query($link,"set names 'utf8'"); //设置字符集
$str = "select * from stu order by Id"." ".$order;
$result = mysqli_query($link,$str);
$arr = array();
while($row = mysqli_fetch_array($result)) {
$arr[]=$row;
}
mysqli_close($link);
?>
<!DOCTYPE html>
<html>
<head>
<title></title>
<style>
table,td
{
border: 1px solid #000;
}
</style>
</head>
<body>
<table cellpadding="1" spacpadding="1">
<tr>
<th>id</th>
<th>姓名</th>
<th>年龄</th>
<th>专业</th>
<th>班级</th>
</tr>
<?php
foreach ($arr as $key => $value)
{
?>
<tr>
<td><?php echo $value[0];?></td>
<td><?php echo $value[1];?></td>
<td><?php echo $value[2];?></td>
<td><?php echo $value[3];?></td>
<td><?php echo $value[4];?></td>
</tr>
<?php }?>
</table>
<a href="?order=<?php echo $order?>">序列</a>
</body>
</html>