PHP自定义函数返回数组值

时间:2016-12-12 14:22:17

标签: php arrays function

我正在尝试使用自定义函数在用户提交数据时显示内联错误。错误位于名为formErrors的数组中,并放在functions.php中。我检查了日志,当页面加载或提交数据时没有显示错误。这是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(); 
}

在index.php中使用$ formErrors数组:

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

我认为错误是$ formErrors ['joke_text']&amp; $ formErrors ['author']但不确定如何检查空字段。

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

答案 0 :(得分:1)

这仅适用于您提交到同一页面的情况。如果要在除您使用的表单或函数之外的其他页面上显示错误,则必须使用$ _SESSION传递数据。也称为flash消息