Is it possible make multiple input field insert in same table_name.
My database design
Php form age form have five input field
<form action="action.php" method="post">
input1
<input type="text" name="age[]">
input2
<input type="text" name="age[]">
input3
<input type="text" name="age[]">
input4
<input type="text" name="age[]">
input5
<input type="text" name="age[]">
<input type="submit" value="submit">
Php script
<?php
$statement = $pdo->prepare("insert into AGEGroup (AGE) values ('$_POST['age']')");
$statement->execute();
echo "Added Successfully.";
?>
It just added one record. how to doing 5 records can all insert in database???
Thank you very much
or use for loop???
<?php
for($i=0, i<$_Post['age'][i],i++){
$statement = $pdo->prepare("insert into AGEGroup (AGE) values ('$_POST['age'][i]')");
$statement->execute();
}
echo "Added Successfully.";
?>
As the query remains the same for all the [x] inserts you should do the prepare outside the loop, so its done only once (saves unnecessary round trips to the server)
Your prepare should also use a parameter rather than concatenate the value directly into the query, to avoid SQL Injection Attack
$stmt = $pdo->prepare("insert into AGEGroup (AGE) values (:age)");
foreach ($_POST['age'] as $age) {
$stmt->execute([':age'=>$age]);
}
While it it possible it is not the best to open connection on each iteration of the forloop.
I would concatenate the whole string and send the query only once.
$query = "";
for($i = 0, $i < $_Post['age'][$i], $i++{
$query .= "INSERT INTO AGEGroup (AGE) VALUES ('{$_POST['age'][$i]}');"
}
$statement = $pdo->prepare($query);
$statement->execute();
Pay attention to $ signs before variable names, in PHP it is marking the upcoming variables for the interpreter.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.