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.

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

报告相同问题?

悬赏问题

  • ¥15 Llama如何调用shell或者Python
  • ¥20 eclipse连接sap后代码跑出来空白
  • ¥20 谁能帮我挨个解读这个php语言编的代码什么意思?
  • ¥15 win10权限管理,限制普通用户使用删除功能
  • ¥15 minnio内存占用过大,内存没被回收(Windows环境)
  • ¥65 抖音咸鱼付款链接转码支付宝
  • ¥15 ubuntu22.04上安装ursim-3.15.8.106339遇到的问题
  • ¥15 blast算法(相关搜索:数据库)
  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?
  • ¥15 网络通信安全解决方案