I tried to store a JavaScript array into MySQL table using PHP, see the following script below.
I first converted the string using JSON.stringify
and passed it into a PHP file via AJAX request.
I then converted it to a PHP array, and after after I inserted those arrays using serialize();
.
Finally, it properly stored using localhost but it does not work on my live server.
sample.Js
$.ajax(
{
type: "POST",
url: "save_plan_ajax.php",
data: {plan: plan,totalInvesment: totalInvesment, location: JSON.stringify(locationsArr), cost: JSON.stringify(cost), personalised: JSON.stringify(personalised)},
success: function(data){
//alert(data);
}
}
)
In this above script I passed the JavaScript array into save_plan_ajax.php using JSON.stringify
.
save_plan_ajax.php
<?php
session_start();
include 'config.php';
if(isset($_POST)){
$planname = $_POST['plan'];
$cost = json_decode($_POST['cost'], true);
$personalised = json_decode($_POST['personalised'], true);
$locations = json_decode($_POST['location'], true);
$userid = $_SESSION['BIID'];
$constriant = $_SESSION['CONSTRAINT'];
$created_date = date("Y-m-d H:i:s");
$total_invs = $_POST['totalInvesment'];
$query = "INSERT INTO `plans` (
`refid` ,
`userid` ,
`plan_name` ,
`cost` ,
`locations`,
`personalised` ,
`total_invs`,
`constriant` ,
`created_date` ,
`stat`
)
VALUES (
NULL , '$userid', '$planname', '".serialize($cost) ."', '".serialize($locations)."','".serialize($personalised)."', '$total_invs', '$constriant', '$created_date', 'A'
)";
$res = $GLOBALS['Db']->Insert($query);
if($res){
echo $res;
}
else{
echo "Error";
}
}
?>
In the above script, the record stores correctly at local server, but in this same script insert N;
in server.. how do I fix this error, is the above way correct?
In the MySQL database table I have set the cost, location and personalized fields datatype as LONGTEXT
.