I have a multiple select form:
<form method="post" action="register_results.php" name="registerform" class="form-horizontal" role="form">
<div class="label">Select Name:</div>
<select name="names" multiple="yes" size="15">
<option value = "">---Select---</option>
<?php
while ( $row=mysqli_fetch_assoc($result)) {
echo "<option value='".$row['registrant_name']."'>".$row['registrant_name']."</option>";
}
mysqli_close($con);
?>
</select>
</form>
The register_results.php file looks like this:
$registrant_name = $_POST['names'];
$event_result = $_POST['result'];
$query = "UPDATE events_regged SET result = $event_result WHERE event_name='event10' AND registrant_name=('$registrant_name') ";
$result = mysqli_query($con, $query);
I want to be able to add multiple mysql rows (one row for each username) if multiple names are selected in the form. How can I do that?
Use
<select name="names[]" multiple="yes" size="15">
instead of
<select name="names" multiple="yes" size="15">
and use foreach
foreach($_POST['names'] as $value)
{
//your query goes here
}
Change the form select element name from "names" to "names[]" and then you can access an array of posted values - which you can then iterate through.
You have some changes required within your code as
<select name="names" multiple="yes" size="15">
^^^^^
it should be
<select name="names[]" multiple size="15">
This will result into an array so the result of
$registrant_name = $_POST['names']
will be an array
First change your form as below (it's more elegant and fast to use Id instead of name (string) in Sql):
<select name="ids[]" multiple size="15">
<option value = "">---Select---</option>
<?php
while ( $row=mysqli_fetch_assoc($result)) {
echo "<option value='".$row['registrant_id']."'>".$row['registrant_name']."</option>";
}
mysqli_close($con);
?>
</select>
And in your PHP use foreach:
$registrant_ids = $_POST['ids'];
$event_result = $_POST['result'];
foreach($registrant_ids as $id)
{
$query = "UPDATE events_regged SET result = $event_result WHERE event_name='event10' AND registrant_id=".$id;
$result = mysqli_query($con, $query);
}