如何使用 PHP 和 MySQL 对表列进行排序

How to Sort Table Columns with PHP and MySQL

在本教程中,我们将使用 HTML、PHP 和 MySQL 对表列进行排序。我们的表将包含来自 MySQL 数据库的记录,HTML 表头将是可点击的,因此用户可以切换是否要按升序或降序(最低或最高)排序。

你可能会问为什么要这样做?它只是允许您的用户与您的表交互的那些功能之一,也许您有一个包含多个页面的表,其中包含数百或数千条记录,并且用户可能希望按特定列排序,例如具有名称 Date,或名称为 Age 的列。

创建 MySQL 数据库

我们需要一个数据库来连接,这样我们就可以在我们的 HTML 表中显示记录。您可以使用现有数据库或使用 phpMyAdmin 或您首选的数据库管理工具运行下面的 SQL 语句。

SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET time_zone = "+00:00";
CREATE DATABASE IF NOT EXISTS `tablesort` DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci;
USE `tablesort`;

CREATE TABLE IF NOT EXISTS `students` (
`id` int(11) NOT NULL,
  `name` varchar(255) NOT NULL,
  `age` tinyint(100) NOT NULL,
  `joined` varchar(255) NOT NULL
) ENGINE=InnoDB AUTO_INCREMENT=42 DEFAULT CHARSET=utf8;

INSERT INTO `students` (`id`, `name`, `age`, `joined`) VALUES
(1, 'David Deacon', 23, '17/08/2018'),
(2, 'Sheri Warner', 19, '03/05/2018'),
(3, 'Sean Glover', 24, '24/07/2018'),
(4, 'John West', 17, '13/08/2018'),
(5, 'Rufus Clarke', 20, '28/07/2018'),
(6, 'Roosevelt Myers', 20, '25/07/2018'),
(7, 'Elvira Andrews', 22, '02/07/2018'),
(8, 'Richard	Cook', 26, '19/07/2018'),
(9, 'Lorenzo	Harris', 23, '01/07/2018'),
(10, 'Eduardo	Hoffman', 17, '03/07/2018'),
(11, 'Jeanne Fisher', 20, '13/08/2018'),
(12, 'Tracy Bowers', 30, '07/07/2018'),
(13, 'Heidi Lawrence', 18, '04/06/2018'),
(14, 'Tara Holland', 25, '01/07/1991'),
(15, 'Grant Edwards', 22, '22/06/2018'),
(16, 'Bradford Green', 29, '02/05/2018'),
(17, 'Gwen Schultz', 20, '02/05/2018'),
(18, 'Hope Dawson', 28, '21/08/2018'),
(19, 'Florence Osborne', 19, '17/05/2018'),
(20, 'Rickey Poole', 26, '28/06/2018'),
(21, 'Casey Sutton', 28, '06/07/2018'),
(22, 'Willie Lowe', 23, '11/05/2018'),
(23, 'Stephen	Schultz', 28, '15/07/2018'),
(24, 'Eileen Lynch', 18, '12/06/2018'),
(25, 'Aaron Ruiz', 29, '02/05/2018'),
(26, 'Mae Murray', 30, '24/06/2018'),
(27, 'Regina Hanson', 21, '26/07/2018'),
(28, 'Cameron	Mclaughlin', 20, '29/07/2018'),
(29, 'Earl Hale', 17, '30/06/2018'),
(30, 'Marta Blair', 24, '10/06/2018'),
(31, 'Alberta	Silva', 22, '05/06/2018'),
(32, 'Joanna Holmes', 20, '20/05/2018'),
(33, 'Alex Brock', 30, '12/05/2018'),
(34, 'Colin Wright', 19, '28/05/2018'),
(35, 'Peter Schmidt', 25, '10/07/2018'),
(36, 'Joshua Price', 27, '13/07/2018'),
(37, 'Elias Chandler', 22, '19/07/2018'),
(38, 'Stanley	Ross', 21, '02/06/2018'),
(39, 'Vera Cole', 26, '02/05/2018'),
(40, 'Johnny Daniels', 29, '19/07/2018'),
(41, 'Yvonne Hopkins', 21, '16/07/2018');


ALTER TABLE `students`
 ADD PRIMARY KEY (`id`);


ALTER TABLE `students`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT,AUTO_INCREMENT=42;

上面的语句将创建数据库表排序与桌子学生,我们将在本教程中使用此表。

使用 PHP 和 MySQL 对表进行排序

现在我们可以继续创建我们的 PHP 文件,创建一个名为的新 PHP 文件表格排序.php.

连接到我们的 MySQL 数据库:

$mysqli = mysqli_connect('localhost', 'root', '', 'tablesort');

让我们创建一些我们将使用的变量:

$columns = array('name','age','joined');
$column = isset($_GET['column']) && in_array($_GET['column'], $columns) ? $_GET['column'] : $columns[0];
$sort_order = isset($_GET['order']) && strtolower($_GET['order']) == 'desc' ? 'DESC' : 'ASC';

下面我将解释每个变量的用途。

$列- 这将是我们将用于表的列数组,这基本上是防止 SQL 注入的安全检查,我们要确保用户不会尝试任何可疑的事情,您可以更改此变量,添加或删除数组中的列名。

$列- 这个变量将决定我们将根据哪一列进行排序,如果它出现在 URL 中,那么它将出现在我们的脚本中,我们还会检查请求的列名是否在我们的$列大批。默认为第一列$列如果没有数组得到要求。

$sort_order- 这个变量将决定排序顺序,基本上,我们可以按升序(ASC)或降序(DESC)排序。如果没有得到请求它将默认为升序。

我们现在可以从我们的数据库表中获取记录。

if ($result = $mysqli->query('SELECT * FROM students ORDER BY ' .  $column . ' ' . $sort_order)) {

并创建更多变量:

$up_or_down = str_replace(array('ASC','DESC'), array('up','down'), $sort_order); 
$asc_or_desc = $sort_order == 'ASC' ? 'desc' : 'asc';
$add_class = ' class="highlight"';

这些变量将做什么:

$up_or_down- 这个变量将与字体真棒一起使用,我们希望那些小的上下图标出现在表格列名旁边,这个变量基本上决定了列的排序方式,并将该图标显示给用户。

$asc_or_desc- 该变量将用于确定活动列的切换状态,是否应该按升序或降序排序,基本上,如果用户已经单击了列名,我们要确保当他们再次单击列名时它将以相反的顺序排序。

$add_class- 这基本上会突出显示活动列,这是可选的,你并不需要它,它只是让表格更吸引人。

现在我们可以按各自的顺序显示记录。

<table>
	<tr>
		<th><a href="tablesort.php?column=name&order=<?php echo $asc_or_desc; ?>">Name<i class="fas fa-sort<?php echo $column == 'name' ? '-' . $up_or_down : ''; ?>"></i></a></th>
		<th><a href="tablesort.php?column=age&order=<?php echo $asc_or_desc; ?>">Age<i class="fas fa-sort<?php echo $column == 'age' ? '-' . $up_or_down : ''; ?>"></i></a></th>
		<th><a href="tablesort.php?column=joined&order=<?php echo $asc_or_desc; ?>">Join Date<i class="fas fa-sort<?php echo $column == 'joined' ? '-' . $up_or_down : ''; ?>"></i></a></th>
	</tr>
	<?php while ($row = $result->fetch_assoc()): ?>
	<tr>
		<td<?php echo $column == 'name' ? $add_class : ''; ?>><?php echo $row['name']; ?></td>
		<td<?php echo $column == 'age' ? $add_class : ''; ?>><?php echo $row['age']; ?></td>
		<td<?php echo $column == 'joined' ? $add_class : ''; ?>><?php echo $row['joined']; ?></td>
	</tr>
	<?php endwhile; ?>
</table>

如您所见,我们使用了我们创建的变量,并且我们还检查了正在排序的表列。这while 循环将从我们的表中循环我们的记录学生并对它们进行相应的排序。

让我们为 HTML 表格添加一些样式,将代码添加到您的 CSS 文件或文档的头部:

table {
	border-collapse: collapse;
	width: 500px;
}
th {
	background-color: #54585d;
	border: 1px solid #54585d;
}
th:hover {
	background-color: #64686e;
}
th a {
	display: block;
	text-decoration:none;
	padding: 10px;
	color: #ffffff;
	font-weight: bold;
	font-size: 13px;
}
th a i {
	margin-left: 5px;
	color: rgba(255,255,255,0.4);
}
td {
	padding: 10px;
	color: #636363;
	border: 1px solid #dddfe1;
}
tr {
	background-color: #ffffff;
}
tr .highlight {
	background-color: #f9fafb;
}

我们还需要 Font Awesome 图标,在文档的 head 部分添加 Font Awesome CDN 代码:

<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.3.1/css/all.css" integrity="sha384-mzrmE5qonljUremFsqc01SB46JvROS7bZs3IO2EmfFsd15uHvIt+Y8vEf7N7fWAU" crossorigin="anonymous">

我们的表格现在应该看起来像这样:


 

完整来源

<?php
// Below is optional, remove if you have already connected to your database.
$mysqli = mysqli_connect('localhost', 'root', '', 'tablesort');

// For extra protection these are the columns of which the user can sort by (in your database table).
$columns = array('name','age','joined');

// Only get the column if it exists in the above columns array, if it doesn't exist the database table will be sorted by the first item in the columns array.
$column = isset($_GET['column']) && in_array($_GET['column'], $columns) ? $_GET['column'] : $columns[0];

// Get the sort order for the column, ascending or descending, default is ascending.
$sort_order = isset($_GET['order']) && strtolower($_GET['order']) == 'desc' ? 'DESC' : 'ASC';

// Get the result...
if ($result = $mysqli->query('SELECT * FROM students ORDER BY ' .  $column . ' ' . $sort_order)) {
	// Some variables we need for the table.
	$up_or_down = str_replace(array('ASC','DESC'), array('up','down'), $sort_order); 
	$asc_or_desc = $sort_order == 'ASC' ? 'desc' : 'asc';
	$add_class = ' class="highlight"';
	?>
	<!DOCTYPE html>
	<html>
		<head>
			<title>PHP & MySQL Table Sorting by CodeShack</title>
			<meta charset="utf-8">
			<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.3.1/css/all.css" integrity="sha384-mzrmE5qonljUremFsqc01SB46JvROS7bZs3IO2EmfFsd15uHvIt+Y8vEf7N7fWAU" crossorigin="anonymous">
			<style>
			html {
				font-family: Tahoma, Geneva, sans-serif;
				padding: 10px;
			}
			table {
				border-collapse: collapse;
				width: 500px;
			}
			th {
				background-color: #54585d;
				border: 1px solid #54585d;
			}
			th:hover {
				background-color: #64686e;
			}
			th a {
				display: block;
				text-decoration:none;
				padding: 10px;
				color: #ffffff;
				font-weight: bold;
				font-size: 13px;
			}
			th a i {
				margin-left: 5px;
				color: rgba(255,255,255,0.4);
			}
			td {
				padding: 10px;
				color: #636363;
				border: 1px solid #dddfe1;
			}
			tr {
				background-color: #ffffff;
			}
			tr .highlight {
				background-color: #f9fafb;
			}
			</style>
		</head>
		<body>
			<table>
				<tr>
					<th><a href="tablesort.php?column=name&order=<?php echo $asc_or_desc; ?>">Name<i class="fas fa-sort<?php echo $column == 'name' ? '-' . $up_or_down : ''; ?>"></i></a></th>
					<th><a href="tablesort.php?column=age&order=<?php echo $asc_or_desc; ?>">Age<i class="fas fa-sort<?php echo $column == 'age' ? '-' . $up_or_down : ''; ?>"></i></a></th>
					<th><a href="tablesort.php?column=joined&order=<?php echo $asc_or_desc; ?>">Join Date<i class="fas fa-sort<?php echo $column == 'joined' ? '-' . $up_or_down : ''; ?>"></i></a></th>
				</tr>
				<?php while ($row = $result->fetch_assoc()): ?>
				<tr>
					<td<?php echo $column == 'name' ? $add_class : ''; ?>><?php echo $row['name']; ?></td>
					<td<?php echo $column == 'age' ? $add_class : ''; ?>><?php echo $row['age']; ?></td>
					<td<?php echo $column == 'joined' ? $add_class : ''; ?>><?php echo $row['joined']; ?></td>
				</tr>
				<?php endwhile; ?>
			</table>
		</body>
	</html>
	<?php
	$result->free();
}
?>


 

结论

这基本上就是您使用 PHP 和 MySQL 对表进行排序的方式,您现在应该对如何创建自己的代码或修改我们现有的代码有一个大致的了解。

这可能需要更多的工作,但如果您想实现页面不重新加载的解决方案,您可以使用 JavaScript 和 AJAX。

如果您还没有,请不要忘记分享这篇文章并在社交媒体上关注我们,更多有用的教程将会出现。享受编码!

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值