未定义的索引错误 - PHP

时间:2014-12-09 23:07:22

标签: php html mysql

我正在设置一个链接,允许用户将配方数据添加到原始页面。数据将通过mysql表并显示在页面上,并显示其他配方。最初的工作原理是INSERT INTO配方(recipe_name)本身,但我需要输入你在下面看到的所有列,但它们没有显示。当我添加其他列时,我得到了未定义的索引错误。我也尝试使用if isset命令,但没有做任何事情。我花了将近一个小时的时间来寻找未定义索引错误的答案,并且没有发现任何与通过网站向数据库添加多个柱状信息相关的内容。

<?php
    if(!empty($_POST)) {
        try
        {
            $sql = 'INSERT INTO recipes 
                        (recipe_name, recipe_ingred, recipe_direct, 
                         author_name, author_email) 
                     VALUES ("' . $_POST['recipe_name, 
                                          recipe_ingred, 
                                          recipe_direct, 
                                          author_name, 
                                          author_email']
                                .'")';
            $result = $pdo->exec($sql);
            header('Location: recipes.php');
        }
        catch (PDOException $e)
        {
            $error = 'Error performing insert: ' . $e->getMessage();
        }
    }
    ?>
    <form method="post">
        <div>
            <label for="recipe_name">Recipe name:</label>
            <input type="text" id="recipe_name" name="recipe_name"><br>
            <label for="recipe_ingred">Recipe ingredients:</label>
            <textarea id="recipe_ingred" name="recipe_ingred" rows="3" cols="40"></textarea><br>
            <label for="recipe_direct">Recipe directions:</label>
            <textarea id="recipe_direct" name="recipe_direct" rows="3" cols="40"></textarea><br>
            <label for="recipe_name">Your name:</label>
            <input type="text" id="author_name" name="author_name"><br>
            <label for="recipe_name">Your email:</label>
            <input type="text" id="author_email" name="author_email"><br>
        </div>
        <div><input type="submit" value="Submit recipe"></div>
    </form>

1 个答案:

答案 0 :(得分:1)

您的语法无效,并且暴露于sql注入,您需要准备查询:

$sql = 'INSERT INTO recipes 
            (recipe_name, recipe_ingred, recipe_direct, author_name, author_email)
        VALUES (?, ?, ?, ?, ?)';
$stmt = $pdo->prepare($sql);
$stmt->execute(array($_POST['recipe_name'], 
                     $_POST['recipe_ingred'], 
                     $_POST['recipe_direct'], 
                     $_POST['author_name'], 
                     $_POST['author_email']));