/path/to/webroot/feeds/add.php
as shown in the following highlighted code:<?php
/**
* File: /path/to/webroot/feeds/add.php
*/
include('init.php'),
// If we have data in POST then get it from there else initialize
// to empty strings
$viewVars['name'] = !empty($_POST['name']) ? $_POST['name'] : '';
$viewVars['url'] = !empty($_POST['url']) ? $_POST['url'] : '';
// Check if form is submitted and if we have a feed name and url
// then save the data
if (!empty($_POST['name']) && !empty($_POST['url'])) {
// First check if the feed being added is already in our database
$stmt = $dbh->prepare("SELECT id FROM feeds WHERE url = :url");
$stmt->bindParam(':url', strip_tags(
$viewVars['url']),
PDO::PARAM_STR);
$stmt->execute();
$result = $stmt->fetch(PDO::FETCH_ASSOC);
// If this is not a duplicate item then only add it
if (empty($result)) {
$stmt = $dbh->prepare("INSERT INTO feeds SET name = :name, url = :url");
$stmt->bindParam(':name', strip_tags($viewVars['name']), PDO::PARAM_STR);
$stmt->bindParam(':url', strip_tags($viewVars['url']), PDO::PARAM_STR);
$stmt->execute();
$viewVars['success'] = true;
$viewVars['name'] = '';
$viewVars['url'] = '';
} else {
$viewVars['error'] = 'This feed has already been added';
}
}
// Render the view
render('add'),
<!-- File: /path/to/webroot/feeds/views/add.thtml -->
<form action="add.php" method="post">
<?php if (!empty($viewVars['success'])): ?>
<div class="information">Feed saved successfully</div><br />
<?php endif; ?>
<?php if (!empty($viewVars['error'])) : ?>
<div class="error"><?php echo $viewVars['error']; ?></div><br />
<?php endif; ?>
<fieldset>
<legend>Add Feed</legend>
<div class="input">
<label>Feed Name: </label>
add.php
file in browser and enter the data as shown in the following screenshot (you may use any name and a valid feed URL).In this exercise, we added the code to save the feed name and URL in the feeds
database table. In add.php
we checked if the form had been posted and then saved the data in the database.
If a feed is added to the database, a success message is shown above the form. This was done by modifying the add.thtml
view and checking for the presence of a success variable.
Lastly, we did some data entry work by adding four different feeds.
If you now open your database (through phpMyAdmin), you will see that the data has been saved there: