dougou8573 2013-01-29 16:42
浏览 64
已采纳

在PHP中解码json时遇到问题

I'm trying to insert an array of 3 digit integers into a MySQL Database (e.g. '301', '302' etc). The array is passed using jQuery, Ajax and JSON into the PHP script. This bit (judging by the 'console.log' function) seems to work fine. The problem comes at the other end when I try to decode the JSON string.

I want each individual item in the array to go into a separate column, but at the moment all that is being inserted into the column is the number '0'.

Code is as follows:

jQuery:

var modules

$('#createbutton').click(function(){
 $('#l3 :checkbox:checked').each(function(i){
  var l3modules = $(this).attr('value');
  modules.push(l3modules);
  });

var modulestransmit = JSON.stringify(modules);
console.log(modulestransmit);

$.ajax({
       url: "newaccount.php",
       type: "POST",
       data: { modules: modulestransmit },
     });
 });

PHP:

 $modules = $_REQUEST['modulestransmit']);
 $insertmodules = json_decode($modules, true);

 if(mysql_query("INSERT INTO level3 (mod1, mod2) VALUES ('$insertmodules[0]', '$insertmodules[1]')")) {
  echo "Successfully inserted";
 }
 else {
  echo "Insertion Failed";
 }

The result in the database is:

mod1: 0

mod2: 0

  • 写回答

1条回答 默认 最新

  • douyabu1528 2013-01-29 16:46
    关注

    You're using modules as the name of the parameter in the request not modulestransmit so change the first line of your PHP to

     $modules = $_REQUEST['modules'];
    

    and you also need to put curly braces around the variable names in the string (vital when referencing arrays in double quotes in PHP).

    "INSERT INTO level3 (mod1, mod2) VALUES ('{$insertmodules[0]}', '{$insertmodules[1]}')"
    

    and that should do it.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥30 VMware 云桌面水印如何添加
  • ¥15 用ns3仿真出5G核心网网元
  • ¥15 matlab答疑 关于海上风电的爬坡事件检测
  • ¥88 python部署量化回测异常问题
  • ¥30 酬劳2w元求合作写文章
  • ¥15 在现有系统基础上增加功能
  • ¥15 远程桌面文档内容复制粘贴,格式会变化
  • ¥15 这种微信登录授权 谁可以做啊
  • ¥15 请问我该如何添加自己的数据去运行蚁群算法代码
  • ¥20 用HslCommunication 连接欧姆龙 plc有时会连接失败。报异常为“未知错误”