good evening everyone, i have a for each loop in php that post only one record to database table. my html code below;
<html>
<input type="hidden" name="username[]" value="<?php echo $userRow['username']; ?>" readonly />
<input type="hidden" name="school[]" value="<?php echo $userRow['school']; ?>" readonly />
<SELECT name='cand_name[]' class='form-control'>
<option></option>
<option>Ahmed MUSA</option>
<option>Ahmed Arinze</option>
<option>NOsa Igiebor</option>
</SELECT>
<SELECT name='cand_name[]' class='form-control'>
<option></option>
<option>Ahmed MUSA</option>
<option>Ahmed Arinze</option>
<option>NOsa Igiebor</option>
</SELECT>
</html>
code below;
<?php
include_once 'dbcon.php';
{
$username = $_POST['username'];
$cand_name = $_POST['cand_name'];
$school = $_POST['school'];
for ($i = 0; $i < count($username); $i++) {
$username = ($username[$i]);
$cand_name = ($cand_name[$i]);
$school = ($school[$i]);
mysqli_query($con, "INSERT INTO parlia (username, cand_name, school) VALUES ('$username', '$cand_name', '$school')");
}
}
i hav checked other SO answers but none seem to work for me. i have edited and it still doesn't work. when i tried this code with input, it worked perfectly but doesn't want to work with options
this piece of code works for me.. you are however susceptible to sql injection
<?php
$username = $_POST['username'][0];
$school = $_POST['school'][0];
$candname = $_POST['candname'];
foreach ($_POST['candname'] as $candname) {
$query = sprintf(
"INSERT INTO parlia_votes (username, school, candname) VALUES ('%s', '%s', '%s')",
$username,
$school,
$candname
);
$con->query($query);
}
?>
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments