Hi,
I am trying to write a form to update a database. The two if() statements which do this are given below in an excerpt from my index.php file
The first if() sets up the form and this is working. However when I submit this form to update I get the error,
You must choose a topic for this topic. Click ‘back’ and try again.
This is of course the actual error message in the second if(). It appears that the form should send $_POST[‘topic’] but seems to be empty.
if (isset($_POST['action']) and $_POST['action'] == 'Edit')
{
include $_SERVER['DOCUMENT_ROOT'] . '/artgibney/includes/db.inc.php';
try
{
$sql = 'SELECT id, topic FROM topics WHERE id = :id';
$s = $pdo->prepare($sql);
$s->bindValue(':id', $_POST['id']);
$s->execute();
}
catch (PDOException $e)
{
$error = 'Error fetching topic row details.';
include 'error.html.php';
exit();
}
$row = $s->fetch();
$pageTitle = 'Edit Topic';
$action = 'editform';
$text = $row['topic'];
$id = $row['id'];
$button = 'Update topic';
// Build the list of topic rows
try
{
$result = $pdo->query('SELECT id, topic FROM topics');
}
catch (PDOException $e)
{
$error = 'Error fetching list of topics.';
include 'error.html.php';
exit();
}
foreach ($result as $row)
{
$topics[] = array('id' => $row['id'], 'topic' => $row['topic']);
}
include 'form.html.php';
exit();
}
if (isset($_GET['editform']))
{
include $_SERVER['DOCUMENT_ROOT'] . '/artgibney/includes/db.inc.php';
if ($_POST['topic'] == '')
{
$error = 'You must choose a topic for this topic.
Click ‘back’ and try again.';
include 'error.html.php';
exit();
}
try
{
$sql = 'UPDATE topics SET
topic = :topic,
WHERE id = :id';
$s = $pdo->prepare($sql);
$s->bindValue(':id', $_POST['id']);
$s->bindValue(':topic', $_POST['text']);
$s->execute();
}
catch (PDOException $e)
{
$error = 'Error updating submitted topic.';
echo $e;
include 'error.html.php';
exit();
}
header('Location: .');
exit();
}
Here is the HTML form,
<?php include_once $_SERVER['DOCUMENT_ROOT'] .
'/artgibney/includes/helpers.inc.php'; ?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title><?php htmlout($pageTitle); ?></title>
<style type="text/css">
textarea {
display: block;
width: 100%;
}
</style>
</head>
<body>
<h1><?php htmlout($pageTitle); ?></h1>
<form action="?<?php htmlout($action); ?>" method="post">
<div>
<label for="text">Type your topic here:</label>
<textarea id="text" name="text" rows="3" cols="40"><?php
htmlout($text); ?></textarea>
</div>
<input type="hidden" name="id" value="<?php
htmlout($id); ?>">
<input type="submit" value="<?php htmlout($button); ?>">
</div>
</form>
</body>
</html>
What am I doing wrong?
Thanks,
Shane