Multiple Parameters in Engine Routes in PHP
Suppose now our site has categories and pages belonging to these categories. Let's create a table with categories:
id | slug | name |
---|---|---|
1 | first-category | name1 |
2 | second-category | name2 |
And a table with pages:
id | slug | title | content | category_id |
---|---|---|---|---|
1 | my-first-page | title1 | <div> content1 </div> | 1 |
2 | my-second-page | title2 | <div> content2 </div> | 1 |
3 | my-third-page | title3 | <div> content3 </div> | 2 |
On our site, we allow page slugs
from different categories to match. This
means that in the URL we must first specify
the category slug, and then the page slug according to
this scheme: /page/:category/:page
,
where the colons indicate the places for
variable parameters.
Let's write the routes for our site:
<?php
$route = '^/page/(?<catSlug>[a-z0-9_-]+)/(?<pageSlug>[a-z0-9_-]+)
;
if (preg_match("#$route#", $url, $params)) {
$page = include 'view/page/show.php';
}
$route = '^/page/(?<catSlug>[a-z0-9_-]+)
;
if (preg_match("#$route#", $url, $params)) {
$page = include 'view/page/category.php';
}
$route = '^/
;
if (preg_match("#$route#", $url, $params)) {
$page = include 'view/page/all.php';
}
?>
In the handler of the first route, we will show the requested page:
<?php
$catSlug = $params['catSlug'];
$pageSlug = $params['pageSlug'];
$query = "SELECT pages.title, pages.content
FROM pages
LEFT JOIN
category ON category.id=pages.category_id
WHERE
pages.slug='$pageSlug' AND category.slug='$catSlug'";
$res = mysqli_query($link, $query) or die(mysqli_error($link));
$page = mysqli_fetch_assoc($res);
return $page;
?>
In the handler of the second route, we will show the list of pages from the specified category:
<?php
$catSlug = $params['catSlug'];
$query = "SELECT pages.slug, pages.title FROM pages
LEFT JOIN
category ON category.id=pages.category_id
WHERE
category.slug='$catSlug'";
$res = mysqli_query($link, $query) or die(mysqli_error($link));
for ($data = []; $row = mysqli_fetch_assoc($res); $data[] = $row);
$content = '';
foreach ($data as $page) {
$content .= '
<div>
<a href="/page/' . $catSlug . '/' . $page['slug'] . '">' . $page['title'] . '</a>
</div>
';
}
$page = [
'title' => 'list of all pages in category ' . $catSlug,
'content' => $content
];
return $page;
?>
Suppose you have a site with cities and countries.
Let the address /
display a list
of all countries, the address /:country
display a list of cities of the country specified in the parameter,
and the address /:country/:city
display the description of the specified city.