【问题标题】:Creating a dynamic link without creating a new .php page/file创建动态链接而不创建新的 .php 页面/文件
【发布时间】:2013-12-28 19:47:28
【问题描述】:

我是 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 等等

任何帮助将不胜感激

【问题讨论】:

    标签: php mysql dynamic hyperlink


    【解决方案1】:

    创建一个名为 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_escape_string()。 http://php.net/manual/en/function.mysql-real-escape-string.php

    【讨论】:

    • 您的示例容易受到 SQL 注入攻击。
    • 像这样,伙计? echo 'CategoryX;
    • 更像&lt;a href="/dev/category.php?cat=a"&gt;CategoryA&lt;/a&gt;&lt;a href="/dev/category.php?cat=b"&gt;CategoryX&lt;/b&gt; 然后在category.php文件中做$_GET代码
    【解决方案2】:

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

     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。但可能会有办法解决这个问题。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-04-01
      • 1970-01-01
      • 1970-01-01
      • 2020-01-22
      • 2019-11-07
      • 1970-01-01
      • 1970-01-01
      • 2014-10-03
      相关资源
      最近更新 更多