1

I have a small PHP website and I use .htaccess to rewrite some URLs.

So far I've removed that .php format from the links and from example.com/page.php now it's example.com/page with this code. It's working great.

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^\.]+)$ $1.php [NC,L] 

Now I'm trying to achieve something different.

I have a news.php and news-view.php pages. The page news.php displays a teaser news list. I'm getting the data from the database with loop and mysql. That works fine. After that I have links on the news title, image and passing the id from the database row.

Here's the code:

<?php
$query = "SELECT * FROM news";
$result = mysqli_query($connection, $query);

while($row = mysqli_fetch_assoc($result)) {
    $id = $row['id'];   
    $title = $row['title'];
    $image = $row['image'];
    $body = $row['body'];

    echo '<li class="news-article">';
    echo '<div class="news-image"><a href="news-view?id=' . $id . '"><img width="400" src="/images/news/' . $image . '"></a></div>';
    echo '<div class="news-title"><a href="news-view?id=' . $id .'">' . $title . '</a></div>';
    echo '<div class="news-body">' . substr($body, 0, 100) .'...' . '</div>';
    echo '</li>';
}
?>  

The page news-view.php displays the passed variables from news.php dynamically and the URL is like this:

www.example.com/news-view?id=(id_number_of_the_news)

My question is: How can I set the pages in this format?

www.example.com/news // displays the news list
www.example.com/news/the_title_of_the_news // displays the specific page

I guess this can be accomplished with .htaccess, but I don't know how.

I've seen lot of websites that has the same URL concept. What is the best practice for displaying news list and specific news pages?

user2519032
  • 819
  • 1
  • 18
  • 34
  • What you've seen in lots of websites are most probably using a PHP MVC framework. Since, what you're trying to achieve is most likely an MVC as well. For the sake of best practice, try to read the concept of MVC. And my suggestion is to go with [Laravel](https://laravel.com/) for it since it's easier to catch up with (imo). And the methodologies that you're looking for is most likely called `routing`. – choz Mar 16 '16 at 15:23
  • Hi, Choz. Thanks for your answer. I'm not using any Framework for now. I'm just starting to read the referenced answer here. Is it possible to achieve easily without using any Frameworks? – user2519032 Mar 16 '16 at 15:58
  • To achieve it easily is just a matter of perspective. But it sure is complicated to me to mess with `.htaccess`. Good luck though – choz Mar 16 '16 at 16:05

0 Answers0