The below code is working fine when you alert it (e.g. it will say "1,2" if Option's 1 and 2 are selected), but when I try to post it using jquery to a database, it simply outputs "Array". I've tried using toString on it, which I thought might help, but it doesn't seem to. The plugin is working fine so I think it must be an error in the way I post it.
How can I get it to post to the database the selected values separated by commas (e.g."1,2") as it does when alerting, instead of "Array"?
HTML
<select id='category' class='category' multiple='multiple'>
<option value='0'>Nothing</option>
<option value='1'>Option 1</option>
<option value='2'>Option 2</option>
<option value='3'>Option 3</option>
</select>
Run the plugin:
$(function(){
$(".category").multiselect();
});
Send to database:
$('.category').change(function() {
var selected = $(this).val();
alert(selected);
$.post('update_db.php', {
content : selected,
id : <?php echo $getid;?>,
set : "column_heading"
})
});
update_db.php works for everything except this multiple selection.
$where = $_POST['id'];
$content = $_POST['content'];
$set = $_POST['set'];
mysqli_query($my_db,"UPDATE my_table SET " . $set . "='" . $content . "' WHERE id=" . $where);
It appears that you send your data to the server in the form of an array. When you cast an array to string in php, it will end up as the string "Array"
.
If you have an array variable $array
, and you append that to a string using the concatenate (put together) operator .
, it might not do what you expect:
$array = array(1, 2, 3);
$foo = 'foo ' . $array; // 'foo Array'
The bigger problem here is that you are creating an SQL query using string concatenation, which leaves you open to SQL injection. You should really consider using PDO or some other abstraction layer that allows for prepared queries, or use escaping.