Dudley Students Dudley Students - 4 days ago 5
PHP Question

PHP form inline validation

Hi I'm having a slight problem in creating an inline form via server-side validation. I have two files, index.php which I am using as a controller to add data to the database and form.php to display the form. This is what I have:

Index.php

<?php
include '../includes/dbconn.php';

# add joke link pressed
if (isset($_GET['add_joke']))
{
// Build the list of authors for drop-down list
try
{
$result = $dbConnection->query('SELECT id, name FROM author');
}
catch (PDOException $e)
{
$error = 'Error fetching list of authors.' . '<br />' . $e -> getMessage();
include '../includes/error.php';
exit();
}

foreach ($result as $row)
{
$authors_in_db[] = array(
'id' => $row['id'],
'name' => $row['name']
);
}
include 'form.php';
exit();
}

# add joke to the database
if (isset($_GET['add_joke_to_db']))
{

# continue with adding joke to the database
try
{
$sql = 'INSERT INTO joke SET
joke_text = :joke_text,
joke_date = CURDATE(),
author_id = :author_id';

$s = $dbConnection -> prepare($sql);
$s -> bindValue(':joke_text', $_POST['joke_text']);
$s -> bindValue(':author_id', $_POST['author']);
$s -> execute();
}
catch (PDOException $e)
{
$error = 'Error adding joke.' . '<br />' . $e -> getMessage();
include '../includes/error.php';
exit();
}

header('Location: .');
exit();
}

# delete joke from the database
if (isset($_GET['delete_joke']))
{
try
{
$sql = 'DELETE FROM joke WHERE id = :id';
$s = $dbConnection -> prepare($sql);
$s -> bindValue(':id', $_POST['id']);
$s -> execute();
}
catch (PDOException $e)
{
$error = 'Error deleting joke.' . '<br />' . $e -> getMessage();
include '../includes/error.php';
exit();
}

header ('Location: .');
exit();
}

# select all jokes from the database
try
{
$sql = 'SELECT joke.id, joke.joke_text, joke.joke_date, author.name, author.email
FROM joke INNER JOIN author
ON author_id = author.id';
$result = $dbConnection -> query($sql);
}
catch (PDOException $e)
{
$error = 'Error fetching jokes.' . '<br />' . $e -> getMessage();
include '../includes/error.php';
exit();
}

# add each data item within an array
foreach ($result as $row)
{
$jokes_in_db[] = array(
'joke.id' => $row['id'],
'joke.joke_text' => $row['joke_text'],
'joke.joke_date' => $row['joke_date'],
'author.name' => $row['name'],
'author.email' => $row['email']
);
}


include 'jokes.php';
?>

and form.php

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Add Joke</title>
<link rel="stylesheet" type="text/css" href="../includes/styles.css" />
</head>
<body>
<h1>Add Joke</h1>
<form action="?add_joke_to_db" method="post">
<div>
<label for="joke_text">Type your joke here:</label>
<textarea id="joke_text" name="joke_text" rows="3" required></textarea>
<span class="error">* <?php echo $joke_textError;?></span>
</div>
<div>
<label for="author">Author:</label>
<select name="author" id="author">
<option value="">Select one</option>
<?php foreach ($authors_in_db as $data): ?>
<option value="<?php echo htmlspecialchars($data['id'], ENT_QUOTES, 'UTF-8'); ?>">
<?php echo htmlspecialchars($data['name'], ENT_QUOTES, 'UTF-8'); ?>
</option>
<?php endforeach; ?>
</select>
<span class="error">* <?php echo $author_textError;?></span>
</div>
<div>
<input type="submit" value="Add">
</div>
</form>
</body>



Answer

Here is the example to set error message for joke_text;

if (isset($_GET['add_joke_to_db']))
{   

$e_joke = 0;
# continue with adding joke to the database
try
{
    if($_POST['joke_text'] == '')
    {
       $e_joke = 1;
    }
    if($e_joke == 0){
    $sql = 'INSERT INTO joke SET
    joke_text = :joke_text,
    joke_date = CURDATE(),
    author_id = :author_id';

    $s = $dbConnection -> prepare($sql);
    $s -> bindValue(':joke_text', $_POST['joke_text']);
    $s -> bindValue(':author_id', $_POST['author']);
    $s -> execute();
  }
 else
 {
  include '../includes/error.php?joke=1';
 }
}
catch (PDOException $e)
{
    $error = 'Error adding joke.' . '<br />' . $e -> getMessage();
    include '../includes/error.php';
    exit();
}

header('Location: .');
exit();
}

Form.php

       <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="utf-8">
        <title>Add Joke</title>
        <link rel="stylesheet" type="text/css" href="../includes/styles.css" />
    </head>
    <body>
        <h1>Add Joke</h1>
        <form action="?add_joke_to_db" method="post">
            <div>
                <label for="joke_text">Type your joke here:</label>
                <textarea id="joke_text" name="joke_text" rows="3" required></textarea>
                <?php
                if(isset($_GET["joke"]))
                { ?>
                <span class="error">* <?php echo "Joke text is missing";?>
               <?php } ?>
</span>
            </div>
            <div>
                <label for="author">Author:</label>
                <select name="author" id="author">
                    <option value="">Select one</option>
                    <?php foreach ($authors_in_db as $data): ?>
                    <option value="<?php echo htmlspecialchars($data['id'], ENT_QUOTES, 'UTF-8'); ?>">
                        <?php echo htmlspecialchars($data['name'], ENT_QUOTES, 'UTF-8'); ?>
                    </option>
                    <?php endforeach; ?>
                </select>
                <span class="error">* <?php echo $author_textError;?></span>
            </div>
            <div>
                <input type="submit" value="Add">
            </div>
        </form>
    </body>

you have to do this logic for all error message like description, joke, etc.

Comments