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
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.