The problem I have is quite logic, but I have never thought of it before and I can not find any documentation about it:
The user will click on the city that he/she wants to get the service from (a city in the UK), but the pages of the cities are all the same with only two differences:
- The title which specifies the city.
- The phone number,which the user will call the company.
<li >
<a href="eletricalpage.php">Electrical</a>
<ul>
<li >
<a href="#">LONDON</a>
<ul>
<li><a href="#">Lewisham</a></li>
<li><a href="#">Greenwich</a></li>
</ul>
</li>
<li >
<a href="#">SOUTH EAST</a>
<ul>
<li><a href="#">Berkshire</a></li>
<li><a href="#">Southampton</a></li>
<li><a href="#">Guildford</a></li>
<li><a href="#">Maidstone</a></li>
<li><a href="#">Brighton</a></li>
</ul>
</li>
<li >
<a href="#">SOUTH WEST</a>
<ul>
<li><a href="#">Bristol</a></li>
<li><a href="#">Swindon</a></li>
</ul>
</li>
Is there any way to avoid building 50 pages for the cities that the company offers its services in? I want to build only one page and then when the user clicks on the city, the page with the changed title and the changed number shows up. I want to get this done in PHP.
CodePudding user response:
You can do as little as create an array containing cities names and the phone number in the pages' script. Later, you can use the global variable $_GET to get the requested city via HTTP GET request to the page.
<?php
$cityPhoneNumbers = [
"London" => "1234-555-1234",
"Manchester" => "1266-555-4321",
];
$requestedCity = $_GET["city"];
if (!empty($requestedCity)) {
if (!empty($cityPhoneNumbers[$requestedCity])) { ?>
Our number in <?=htmlspecialchars($requestedCity) ?> is <?= $cityPhoneNumbers[
$requestedCity
] ?>
<?php }
}
?>
You can now link to this page like this: /number.php?city=London To avoid using the question mark in your URL you may use Apache mod_rewrite or similar.
CodePudding user response:
Try this:
php:
// getInfo.php
<?php
$cities = [
'Lewisham' => ['title' => 'Title for Lewisham', 'phone_number' => ' 41xxxxxxx'],
'Greenwich' => ['title' => 'Title for Greenwich', 'phone_number' => ' 41xxxxxxx'],
// And more...
];
// Get the city name from input
$city = htmlspecialchars($_GET['city']);
// Get the city information from your data
$city_info = $cities[$city];
if(!$city_info){
exit(404);
}
// Include your single page to display information
include "displayInfo.php";
php:
// displayInfo.php
<html>
<head>
<title><?=$city_info['title']?></title>
</head>
<body>
Phone number in <?=$city?> is: <?=$city_info['phone_number']?>
</body>
</html>
And in your html you should link the cities to the getInfo.php file like this:
<li><a href="getInfo.php?city=Lewisham">Lewisham</a></li>
Notice: