简体   繁体   中英

Getting data from a multiple select dropdown with PHP to insert into MySQL

I have a list of days in my database created with the SET datatype.

SET('Mon','Tue','Wed','Thr','Fri','Sat','Sun')

I want a user to be able to select multiple days to put into the database using a multiple select dropdown:

<select name='days' id='days' size=4 multiple>
<option name=Mon value=Mon> Mon </option>
<option name=Tue value=Tue> Tue </option>
<option name=Wed value=Wed> Wed </option>
<option name=Thr value=Thr> Thr </option>
<option name=Fri value=Fri> Fri </option>
<option name=Sat value=Sat> Sat </option>
<option name=Sun value=Sun> Sun </option>
</select>

How can I grab the data from this dropdown to insert into my mysql query?

Right now my query is like this:

$sql2 = " UPDATE tblFacilityHrsDateTimes SET `startEventDate`='{$_POST['startEventDate']}',`endEventDate`='{$_POST['endEventDate']}', `startTime`='{$_POST['startTime']}',`endTime`='{$_POST['endTime']}',`recurrence`='{$_POST['recurrence']},`finalDate`='{$_POST['finalDate']}' WHERE `id` = '$id' "; $mysqli->query($sql2) or die($mysqli->error);

Currently with the select box as is, it only grabs one of the days selected by a user.

First, Your select should have name with square brackets:

<select name='days[]' id='days' size=4 multiple="multiple">

This way when a user select more values (options) and submit the form You will receive an array of values he selected.

Then You have to loop through this array and insert each record:

foreach($_POST['days'] as $k => $v) {
    // here do the INSERT query with value $v
}

But Your query under the select box is telling us that this is not the end of the story...

foreach ($_POST['days'] AS $key => $value) {
  // INSERT ... where $value is one of the values
}

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM