在不创建新的.php页面/文件的情况下创建动态链接


Creating a dynamic link without creating a new .php page/file

我是PHP的新手,我正在寻找可能的方法来创建动态链接,而不创建新的.PHP页面/文件

所以,我正在编写一个博客,对帖子进行分类。A类、B类、C类等等。

我的桌子

id int(11)
title varchar(255)
post_category varchar(50)
post_content text
num_comments int(11)
date_posted date

这就是帖子类别设置的方式

foreach ($category as $cat=>$value) {
    $post_category = "";
    $post_category .= $value." ";
}

带有复选框

<input type="checkbox" name="category[]" value="CategoryA"> CategoryA 
<input type="checkbox" name="category[]" value="CategoryB"> CategoryB
<input type="checkbox" name="category[]" value="CategoryC"> CategoryC

在index.php中,我需要知道如何创建动态链接,如A类、B类等。

这些链接包含根据其类别的帖子,而不创建文件CategoryA.php CategoryB.php等

如有任何帮助,将不胜感激

创建一个名为category.php的php文件,然后用get变量传递您感兴趣的类别。例如category.php?cat=A会让你进入A类。你可以像这样阅读这个变量echo $_GET["cat"]。如果你想了解更多信息,请点击此处:http://php.net/manual/en/reserved.variables.get.php

在您的sql中,您将希望选择您的类别,如下所示:

SELECT * FROM `your_table_name` WHERE `post_category` like '%'".$cat."'%'  

根据您的PHP版本,您应该在用作mysql查询的任何输入周围使用mysql_real_eescape_string()。http://php.net/manual/en/function.mysql-real-escape-string.php

在您的博客页面上创建一个带有:的链接

 while ($row = mysqli_fetch_array($posts)) {
     // your code to display your content here
     // this ill create a link with a GET request and is passed with the post ID
     echo '<a href="category.php?id='.$row['category']'"><button class="read-more">Read More
     </button>  </a>'; 
 }

在您的分类页面上:

// get post category from GET
$cat = $_GET['category'];
$dbc = mysqli_connect(DB_HOST,DB_USER,DB_PASSWORD,DB_NAME) or die('Error connecting to server');
$query = "SELECT * FROM posts WHERE category = '$cat'";
$posts = mysqli_query($dbc,$query);
while ($row = mysqli_fetch_array($posts)) {
    // your code to display your single post content here                   
}

不利的一面是你没有内容的永久链接。它永远都是这样category.php?id=SomeRandomNumber。但可能会有办法解决这个问题。

相关文章: