Diego Tedesco
Diego Tedesco

Reputation: 21

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

I'm developing a news website with php-mysql.


This is the table:

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
)";

on the index page of the website will be shown the articles.


$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";
}

WHAT I NEED? i don't know how to create automatic pages and links for the single articles. EXAMPLE: www.website.com/this-is-the-title-of-the-article. i was thinking about using the id of the db table,but how to select one precise row? can you help me? thanks!!! ;)

Upvotes: 2

Views: 105

Answers (1)

apokryfos
apokryfos

Reputation: 40720

One idea. First of all, you need to add a slug field in your table (https://en.wikipedia.org/wiki/Semantic_URL#Slug) which will hold the title in the form of this-is-the-title-of-the-article.

The assumption here would be that the "slug" will need to be a unique string in the table.

Secondly, you need to use some sort of rewrite mechanism (e.g. apache's mod_rewrite) to convert request of the form www.website.com/this-is-the-title-of-the-article to something you can handle via a PHP script. For example www.website.com/this-is-the-title-of-the-article gets rewritten as as www.website.com/index.php?q=this-is-the-title-of-the-article).

Example .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
}

I understand this is a very vague description and this is only one way of doing it. I would personally suggest you look into an MVC framework like e.g. Laravel which has all of this functionality already built in.

Upvotes: 1

Related Questions