2013-08-19 29 views
0

我試圖插入多個選擇值到數據庫。如何將多個選擇值插入數據庫?

HTML

<select style="width:175px" id="first" multiple="true"> 
    <option value="1">1</option> 
    <option value="2">2</option> 
    <option value="3">3</option> 
    <option value="4">4</option> 
    <option value="5">5</option>   
</select> 
</div> 

<div class="mid"> 
<button type="button" class='add'> > </button> 
<button type="button" class='remove'> < </button> 
<button type="button" class='add-all'> >>> </button> 
<button type="button" class='remove-all'> <<< </button> 
</div> 

<div class="end"> 
<select style="width:175px" id="second" name="second[]" multiple="true"> 
</select> 
</div> 

<div style="clear:both;"></div> 

使用Javascript:

$('.add').click(function(){ 
$('#first option:selected').appendTo('#second'); 
}); 
$('.remove').click(function(){ 
$('#second option:selected').appendTo('#first'); 
}); 
$('.add-all').click(function(){ 
$('#first option').appendTo('#second'); 
}); 
$('.remove-all').click(function(){ 
$('#second option').appendTo('#first'); 
}); 

PHP:(其僅PHP代碼的一小部分)

$formvars['second'] = $this->Sanitize($_POST['second']); 
$insert_query = 'insert into 'comments'(second) values ("' . $this->SanitizeForSQL($formvars['second']) . '",)'; 

及其插入只單詞 「陣列」 到數據庫。任何想法?

+0

這是因爲你的代碼$ this-> SanitizeForSQL($ formvars ['second'])返回一個數組,並且它不能以這種方式插入。查找批量插入查詢。 –

回答

0
var selectArr = []; 

$('#first option').each(function() { 
    selectArr.push($(this).val()); 
}); 

現在你可以將selectArr傳遞給你的服務器,然後檢查你得到了什麼。

0

如果它插入一個數組,你應該就可以通過對循環加入所有的值在一個字符串迭代:

<?php 
    $toInsert = ''; 
    foreach($_POST['second'] as $p){ 
     $toInsert = $toInsert . $p; 
    } 
?> 

的$ toInsert字符串是你應該寫爲DB的一個。