[英]Insert multiple select values with ajax and PDO
Im trying to insert my multiple select values to my database.我试图将我的多个 select 值插入我的数据库。 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:
<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 Ajax代码
$(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.在 AJAX 请求中发送值数组。
$(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.然后在 PHP 中,您需要遍历数组,将每个值插入到表的不同行中。
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
));
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.