我有一个动态形式,可以添加和删除 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
循环中。
原始SQL看起来像是尝试使用prepared statements
的尝试
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") );
}
您将$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注入的准备陈述