简体   繁体   中英

How to put checkbox values into a PHP array

I am having trouble getting the values from checkboxes into my database, it just shows up as 'Array' when submitted to the database.

Here are snippets of my code that illustrate what I am trying to do:

HTML:

<input type="checkbox" name="commentType[]" id="Streams_Wetlands" value="Streams_Wetlands">
<input type="checkbox" name="commentType[]" id="Vegetation" value="Vegetation">

JS:

 var commentType = new Array(); 
 $('input:checkbox[name="commentType[]"]').each(function() {
       commentType.push($(this).val());
 });

 postData( "php/add1.php",{
    CommentAddress1: commentAddress1,
    UserAddress1: userAddress1,
    CommentType1: commentType,
    CommentTypeOther1: commentTypeOther1
  });

PHP:

$q .= " . $_POST['UserAddress1'] . "','" . $_POST['CommentType1'] . "','" . $_POST['CommentTypeOther1'] . "','" . $_POST['CommentAddress1'] . ";

JSON encode the array before storing it into database.

var commentType = new Array(); 
 $('input:checkbox[name="commentType[]"]').each(function() {
       commentType.push($(this).val());
 });

 var comments = JSON.stringify(commentType);

Then store the json string into database.

As usual you'll run a query to fetch data from database. Since you stored it as a json string into database, you can't use it as an array. In order to convert the json string back to an array, use json_decode() .

$CommentsArray = json_decode($commentJsonStringFromDB, true);

Why we did all this ? Because we had to serialise the array before storing it into database, Why ? Because by serialising, we :

Generates a storable representation of a value. This is useful for storing or passing PHP values around without losing their type and structure.

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