如何使用php自动创建页面?(里面有更多细节)


How to create pages automatically with php? (More details inside)

我正在用php-mysql开发一个新闻网站。


这是表格:

news_id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
news_title VARCHAR(250) NOT NULL,
news_short_description TEXT NOT NULL,
news_full_content TEXT NOT NULL,
news_author VARCHAR(30) NOT NULL,
news_published_on DATE NOT NULL
)";

在网站的索引页面上会显示文章。


$sql = "SELECT news_id,news_title,news_short_description,news_full_content,news_author,news_published_on FROM ARTICOLI ORDER BY news_id DESC LIMIT 10";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
    // output data of each row
    while($row = $result->fetch_assoc()) {
        echo "<h3>". $row["news_title"]. " </h3><br> " . $row["news_short_description"]. "<br> " ."Posted by ". $row["news_author"]. "<br>";
    }
} else {
    echo "0 results";
}

我需要什么?我不知道如何为单个文章创建自动页面和链接。示例:www.website.com/this-is-the-time-of-the-article。我在考虑使用db表的id,但是如何选择一个精确的行呢?你能帮我吗?谢谢!!!)

一个想法。首先,您需要在表中添加一个段塞字段(https://en.wikipedia.org/wiki/Semantic_URL#Slug)其将保持CCD_ 1形式的标题。

这里的假设是,"slug"需要是表中唯一的字符串。

其次,您需要使用某种重写机制(例如apache的mod_rewrite)将形式为www.website.com/this-is-the-time-of-the-article的请求转换为可以通过PHP脚本处理的请求。例如,www.website.com/this-is-the-time-of-the-article被重写为www.websitecom/index.php?q=这是文章的标题)。

示例.htaccess

RewriteRule ^(.*)$ /index.php?q=$1 [L] 

index.php

<?php 
 $articleSlug = isset($_GET(["q"])?$_GET["q"]:null;
 if ($articleSlug !== null) {
     $query = "SELECT news_id,news_title,news_short_description,news_full_content,news_author,news_published_on FROM ARTICOLI WHERE slug=?"; // Bind the ? to $articleSlug
      //Execute SQL here and echo the results
} else {
   // 404 error
}

我知道这是一个非常模糊的描述,这只是一种方法。我个人建议你研究一个MVC框架,比如Laravel,它已经内置了所有这些功能。