Im trying to insert my multiple select values to my database. I've tried using multiple ways to add but i can't get it to work. I'm passing the selected values in a hidden textbox (in this example is not hidden). Here is part of the code:
The select:
<select class="form-control" multiple="multiple" id="services" style="height: 36px;width: 100%; border: 1px solid #ccc;">
<?php
$services = get_all_services();
foreach ($services as $s) { ?>
<option value="<?php echo safe_output($s["service_id"]); ?>"><?php echo safe_output($s["service_name"]); ?></option>
<?php } ?>
</select>
<input type="text" name="hidden_service" id="hidden_service" />
Ajax code
$(document).on("click", "#submit", function(e){
e.preventDefault();
var services = $('#hidden_service').val($('#services').val());
$.ajax({
url: 'auths/add-dealers.php',
type: 'POST',
data: {
services:services
}, success: function(data){
$("#result").html(data);
}
})
$("#form")[0].reset();
});
Insert Method:
if(isset($_POST['hidden_service'])){
$services = safe_input($_POST['hidden_service']);
$sql="INSERT INTO " . TBL_DEALER_SERVICES . "(`dealer_id`, `service_id`) VALUES (:dealer, :services)";
$stmt = $DB->prepare($sql);
$stmt->execute(array(
':dealer' => $lastDealer,
':services' => $_POST['hidden_service']
));
}
There's no need for the hidden input. Send the array of values in the AJAX request.
$(document).on("click", "#submit", function(e){ e.preventDefault(); $.ajax({ url: 'auths/add-dealers.php', type: 'POST', data: { services: $("#services").val() }, success: function(data){ $("#result").html(data); } }) $("#form")[0].reset(); });
Then in PHP, you need to loop over the array, inserting each value into a different row of the table.
if(isset($_POST['services'])){
$sql="INSERT INTO " . TBL_DEALER_SERVICES . "(`dealer_id`, `service_id`) VALUES (:dealer, :services)";
$stmt = $DB->prepare($sql);
foreach ($_POST['services'] as $service) {
$stmt->execute(array(
':dealer' => $lastDealer,
':services' => $service
));
}
}
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.