【问题标题】:How to put checkbox values into a PHP array如何将复选框值放入 PHP 数组
【发布时间】:2015-08-06 16:43:35
【问题描述】:

我无法从复选框中获取值到我的数据库中,它在提交到数据库时只是显示为“数组”。

这里是我的代码的 sn-ps,说明了我正在尝试做的事情:

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'] . ";

【问题讨论】:

    标签: javascript php arrays forms


    【解决方案1】:

    在将数组存储到数据库之前对数组进行 JSON 编码。

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

    然后将json字符串存入数据库。

    像往常一样,您将运行查询以从数据库中获取数据。由于您将其作为 json 字符串存储到数据库中,因此不能将其用作数组。要将 json 字符串转换回数组,请使用 json_decode()

    $CommentsArray = json_decode($commentJsonStringFromDB, true);
    

    我们为什么要这么做?因为我们必须在将数组存储到数据库之前对其进行序列化,为什么?因为通过序列化,我们:

    生成一个值的可存储表示。这对 在不丢失类型的情况下存储或传递 PHP 值 结构。

    【讨论】:

    • 什么是 $someJsonString?我不明白关于解码 JSON 的第二部分。
    • 所以现在将值添加到我的数据库中,但包括 ["",""]... 像这样:["Agriculture","Grazing","Biological","Streams_Wetlands" “植被”、“安全”、“噪音”、“受保护物种”、“财产”、“一般建筑”、“地面干扰”、“RightOfWayAccess”、“视觉影响”、“其他”]。如何摆脱格式并仅使用逗号分隔列表?
    • 即json字符串格式。将其存储为 json 字符串而不是逗号分隔值的优点在于,您始终可以使用默认的 php 函数轻松地将其转换回数组,正如我在答案中提到的那样。
    • 好的,但是我需要将它作为数组发送到数据库。我该怎么做?
    • 您必须序列化一个数组才能将其存储到数据库中,这就是我们将其编码为 json 的原因。
    猜你喜欢
    • 1970-01-01
    • 2016-03-24
    • 1970-01-01
    • 1970-01-01
    • 2015-05-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多