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.

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

报告相同问题?