I have a database called dbcenter and I Have Courses table. I have form to insert multiple courses names at the same time. But when I do submit it only insert one empty row. This is my input FORM :
<form action="COURSE.php" method="POST" enctype='multipart/form-data'>
<input type="text" name="listName[]" value="course 1">
<input type="text" name="listName[]" value="course 2">
<input type="text" name="listName[]" value="course 3">
<input type="submit" name="submit" value="insert">
</form>
And my PHP code:
if(isset(filter_input_array(INPUT_POST)['submit'])){
$names[] = filter_input(INPUT_POST,'listName');
if(is_array($names)){
foreach ($names AS $key => $item){
$insertCourse = $con->prepare("INSERT INTO `courses`(`course_Name`)
VALUES ('$item')");
}
$insertCourse->execute();
if($insertCourse){
echo 'added';
}
}
else {
echo 'not array';
}
}
I tried to remove [] from input names listName[],and it inserts data but only last textbox. Any one can help me in this ?
There is error in filtering input.
execute()
should be inside foreach loop.
Also never trust user input, use parameterized queries or escape with mysqli::real_escape_string()
, so that user input is properly escaped:
if(isset(filter_input_array(INPUT_POST)['submit'])){
$names = filter_input_array(INPUT_POST)['listName'];
if(is_array($names)){
$insertCourse = $con->prepare("INSERT INTO `courses`(`course_Name`)
VALUES (?)");
$insertCourse->bind_param("s", $item);
foreach ($names AS $key => $item){
$res = $insertCourse->execute();
if($res){
echo 'added<br>';
}
}
$insertCourse->close();
}
else {
echo 'not array';
}
}