<?php
//case 12 员工信息排序
/*
*建立数据表的sql语句
*
* create table emp_info(
emp_id int unsigned auto_increment primary key,
emp_name varchar(20) not null,
emp_dept varchar(20) not null,
date_birth timestamp not null,
date_entry timestamp not null
)charset = utf8;
insert into emp_info values(1,'张三','推广部','1980-05-01','2020-01-10');
insert into emp_info values(2,'李四','人资部','1980-05-01','2020-01-10');
insert into emp_info values(3,'王五','公关部','1980-05-01','2020-01-10');
insert into emp_info values(4,'麻六','销售部','1980-05-01','2020-01-10');
insert into emp_info values(5,'小兰','人事部','1989-4-5','2015-1-4');
insert into emp_info values(6,'小新','广告部','1993-8-19','2016-2-24');
insert into emp_info values(7,'小白','财务部','1991-10-5','2017-8-14');
insert into emp_info values(8,'小智','运维部','1978-11-25','2000-3-19');
*
*/
header('Content-type:text/html;charset=utf8');
$connect = mysqli_connect('localhost','root','mysql123','test');
if(!$connect)
{
die('数据库连接失败!'.mysqli_error());
}
//mysql中字符集是utf8,不是uft-8
mysqli_query($connect,"set names utf8");
//排序数组
$fields = array('emp_dept','date_entry');
//排序语句
$sql_order = '';
//获取排序字段
$order = isset($_GET['order'])?$_GET['order']:'';
//或许排序方式
$sort = isset($_GET['sort'])?$_GET['sort']:'';
//排序字段在排序数组中的
if(in_array($order,$fields))
{
//降序
if($sort == 'desc')
{
$sql_order = " order by $order desc";
//修改为升序
$sort = 'asc';
}
//升序
else
{
$sql_order = " order by $order asc";
//修改降序
$sort = 'desc';
}
}
//拼接字符串
$sql = "select * from emp_info ".$sql_order;
$result = mysqli_query($connect,$sql);
$emp_info = array();
while($row = mysqli_fetch_assoc($result))
{
$emp_info[] = $row;
}
?>
<html>
<head>
<meta charset="UTF-8">
<title>员工信息列表</title>
</head>
<body>
<div>员工信息列表</div>
<form method="get" action="">
<table border="1" cellspacing="0" cellpadding="0" width="50%" style="text-align: center;">
<tr>
<th>ID</th>
<th>姓名</th>
<th><a href="./t199.php?order=emp_dept&sort=<?php echo ($order == 'emp_dept')?$sort:'desc';?>">部门</a></th>
<th>出生日期</th>
<th><a href="./t199.php?order=date_entry&sort=<?php echo ($order == 'date_entry')?$sort:'desc';?>">入职时间</a></th>
<th width="25%">相关操作</th>
</tr>
<?php
if(!empty($emp_info))
{
foreach ($emp_info as $row1)
{
echo "<tr>";
echo "<td>{$row1['emp_id']}</td>";
echo "<td>{$row1['emp_name']}</td>";
echo "<td>{$row1['emp_dept']}</td>";
echo "<td>{$row1['date_birth']}</td>";
echo "<td>{$row1['date_entry']}</td>";
echo "<td><span>编辑 删除</span></td>";
echo "</tr>";
}
}
else
{
echo "<tr><td colspan='6'>暂无员工数据!</td></tr>";
}
mysqli_free_result($result);
mysqli_close($connect);
?>
</table>
</form>
</body>
</html>