0

I have a slight problem. I am trying to create a custom functions in PHP but I get an “undefined variable error” on form.php for lines 14 and 26 which are the $formErrors ones. Any chance someone can take a look? Here are my files:

index.php

<?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();
    }
}
?>

functions.php

<?php
include '../includes/dbconn.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(); 
}

?>

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"></textarea>
                <span class="error"><?php echo $formErrors['joke_text'];?></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 $formErrors['author'];?></span>
            </div>
            <div>
                <input type="submit" value="Add">
            </div>
        </form>
    </body>
</html>

2 Answers2

0

$formErrors is not set check with isset($formErrors) change your form.php.

like this

<?php if(isset($formErrors)){ ?>
  <span class="error"><?php echo $formErrors['joke_text'];?></span>
<?php } ?>
D Coder
  • 572
  • 4
  • 16
0

This will solve your issue. On first time load obviously you won't get any error and $formErrors is not set so it's giving error.

   <!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>
Akshay
  • 700
  • 9
  • 23