0

I am trying to use a custom function to display inline errors when a user submits data. The errors are in an array named formErrors and are placed within functions.php. I've checked the logs and there are no errors displayed when the page loads or when the data is submitted. This is functions.php

function formErrors()
{
    $formErrors = array();
    $formErrors['joke_text'] = '';
    $formErrors['author'] = '';
    return $formErrors;
}

function listAuthors()
{
    global $dbConnection;
    // get list of authors
    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();
    }

    // add values into array
    foreach ($result as $row)
    {
        $authors_in_db[] = array(
        'id' => $row['id'], 
        'name' => $row['name']
        );
    }

    //Call the form script
    include 'form.php';
    exit(); 
}

In index.php is where $formErrors array is used:

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

# add joke link pressed
if (isset($_GET['add_joke']))
{   
    $formErrors = formErrors();
    listAuthors();

}

# add joke to the database
if (isset($_GET['add_joke_to_db']))
{   
    # check for empty fields
    if (trim(($_POST['joke_text'] == '')))
    {
        $formErrors['joke_text'] = '* Joke text field cannot be empty.';
    }
    if (trim(($_POST['author'] == '')))
    {
        $formErrors['author'] = '* Author field cannot be empty.';
    }

    # if errors found, show the form again
    if (!empty($formErrors)) 
    {
        listAuthors();
    }   
    else 
    # else if no errors found, 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();
    }
}
?>

The error I think is with $formErrors['joke_text'] & $formErrors['author'] but unsure of how to get it to check the empty fields.

This is 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"></textarea>
                <?php if(isset($formErrors)){ ?>
                    <span class="error">
                <?php echo $formErrors['joke_text'];?></span><?php } ?>
            </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>
                 <?php if(isset($formErrors)){ ?>
                    <span class="error"><?php echo $formErrors['author'];?></span> <?php } ?>
            </div>
            <div>
                <input type="submit" value="Add">
            </div>
        </form>
    </body>
</html>
1
  • I didn't understand you question? What's happening? And Why put exit(); in severals places in your code? Commented Dec 12, 2016 at 15:36

1 Answer 1

1

This only works if you submit to the same page. if you want to display errors on other pages than where your form or function you use is, then you have to use $_SESSION to pass around the data. Also known as flash messages

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.