PHP / MySQL - foreach循环$ _POST插入数据库无法正常工作

时间:2017-06-26 06:42:13

标签: php mysql

我有一个动态表单,可以添加和删除textarea个元素。我正在尝试使用for循环将这些元素插入到MySQL数据库中。

<?php 

//if upload button is pressed
if (isset($_POST['upload'])) {

    //connect to the database
    $db = mysqli_connect('', '', '', '');

    $sql = "INSERT INTO table (paragraph) VALUES ('$paragraph')";

    $i = 0;
    foreach ($_POST as $value){
        $paragraph = $_POST['paragraph'][$i];
        mysqli_query($db, $sql);
        $i++;
    }

    header("location: form.php");
    exit;

}

?>

<html>
<body>

    <form method="post" action="form.php">

        <input type="submit" name="upload" value="Upload" id="upload">

    </form>

    <button onclick="addParagraph()">Add Paragraph</button>



</body>
</html>

<script>

//add paragraph div
function addParagraph() {
    $("form").append('<div><textarea name="paragraph[]"></textarea><button class="remove">Remove</button></div>');
}

//remove paragraph div
$(document).on('click', ".remove", function(e) {
    $(this).parent().remove();
});



</script>

不幸的是,这似乎将空字段输入数据库。我相信问题发生在php代码中的foreach循环中。

2 个答案:

答案 0 :(得分:3)

原始的sql类似于尝试使用prepared statements - 但是很容易被sql注入 - 你应该能够做到这样的事情:

if ( isset($_POST['upload']) ) {

    //connect to the database
    $db = mysqli_connect('', '', '', '');

    $sql = "INSERT INTO table ( paragraph ) VALUES ( ? )";
    $stmt=$db->prepare($sql);

    if( $stmt ){

        $stmt->bind_param('s',$paragraph);

        foreach ( $_POST['paragraph'] as $paragraph){
            $stmt->execute();
        }
        $stmt->close();
    }
    exit( header("location: form.php") );
}

答案 1 :(得分:1)

您可以将$paragarph的值分配给此行中的SQL语句:

$sql = "INSERT INTO table (paragraph) VALUES ('$paragraph')";

这里的值为空,这就是数据库中为空的原因。

您必须将语句放在循环中:

 foreach ($_POST['paragraph'] as $value){
        $paragraph = value[$i];
        $sql = "INSERT INTO table (paragraph) VALUES ('$paragraph')";
        mysqli_query($db, $sql);
        $i++;
    }

正如我在评论中所说:

了解用于防止SQL注入的预准备语句