Adding a Tour

Let's create a form to let users provide the tour data themselves.

Creating a form for tour data

What we really want is for the user to provide the data themselves, so we can save it. Let’s start by adding includes for the good old _header.php and _footer.php files and showing a form for tour data.

Press + to interact
<?php
// ...
// Save the tours data to `data/tours.json`:
file_put_contents($toursJsonFile, $jsonData);
include(__DIR__ . '/../_header.php');
?>
<h1>Create a new tour</h1>
<form method="post">
<div>
<label for="destination">
Destination:
</label>
<input type="text" name="destination" id="destination">
</div>
<div>
<label for="number_of_tickets_available">
Number of tickets available:
</label>
<input type="number" name="number_of_tickets_available"
id="number_of_tickets_available">
</div>
<div>
<label>
<input type="checkbox" name="is_accessible" value="yes">
Is accessible
</label>
</div>
<div>
<button type="submit">Save</button>
</div>
</form>
<?php
include(__DIR__ . '/../_footer.php');

The new form looks like this:

Using submitted data to add a new tour

Note that because the form element has its method attribute set to "post", the submitted data will end up in the $_POST superglobal. Let’s take the data out and add it to $toursData instead of the hard-coded trip to Berlin:

Press + to interact
<?php
// ...
$toursJsonFile = __DIR__ . '/../data/tours.json';
if (file_exists($toursJsonFile)) {
// ...
} else {
// ...
}
/*
* If the request method is POST,
* then use the submitted data to save the new tour:
*/
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$toursData[] = [
'destination' => $_POST['destination'],
'number_of_tickets_available' =>
$_POST['number_of_tickets_available'],
'is_accessible' => $_POST['is_accessible']
];
}
// ...
file_put_contents($toursJsonFile, $jsonData);

Now go to http://APPLINK/create-tour again, fill out the form ...

Access this course and 1400+ top-rated courses and projects.