PHP - 创建自定义函数

时间:2016-12-12 11:48:03

标签: php function

我有一个小问题。我试图在PHP中创建自定义函数,但我在form.php上得到第14和26行的“未定义变量错误”,它们是$ formErrors。有人可以看看吗?这是我的文件:

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

?>

和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 个答案:

答案 0 :(得分:0)

$ formErrors未设置,请isset($formErrors)更改您的form.php

喜欢这个

<?php if(isset($formErrors)){ ?>
  <span class="error"><?php echo $formErrors['joke_text'];?></span>
<?php } ?>

答案 1 :(得分:0)

这将解决您的问题。在第一次加载时,显然您不会收到任何错误,并且$formErrors未设置,因此它会给出错误。

   <!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>