在PHP中实现博客分类的方法有很多种,这里我将向您介绍一种简单的方法,使用数组和循环来实现分类。
CREATE TABLE `categories` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(255) NOT NULL,
`description` text NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
<?php
// 连接数据库
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "blog_database";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("连接失败: " . $conn->connect_error);
}
// 获取分类信息
$sql = "SELECT * FROM categories";
$result = $conn->query($sql);
$categories = [];
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$categories[] = $row;
}
} else {
echo "0 结果";
}
$conn->close();
?>
<?php
// 输出分类
foreach ($categories as $category) {
echo "<h2>" . $category['name'] . "</h2>";
echo "<p>" . $category['description'] . "</p>";
}
?>
这样,您就可以在博客中显示分类了。当然,您还可以根据需求对分类进行排序、筛选等操作。