I’m not a PHP developer so I may be doing something wrong. I’m trying to decode JSON string and insert some values to mysql database. I’m getting a valid array of json objects (tested with jsonlint), so I’m adding them one by one to database. But php throws :
<b>Fatal error</b>: Cannot use object of type stdClass as array error.
This is the code :
$array = json_decode(stripslashes($_POST['data']));
for($i = 0, $l = sizeof($array); $i < $l; $i++){
$obj = $array[$i];
echo "ARRAY1: ".$array;
echo "L: ".$l;
echo "ARRAY2: ".gettype($array);
$q = 'INSERT INTO dependencies SET projectID = "1", `from` = "'.$obj->{'From'}.'", to = "'.$obj->{'To'}.'", type = "'.$obj->{'Type'}.'", cls = "'.$obj->{'Cls'}.'", lag = "'.$obj{'Lag'}.'"';
Error is thrown from line $q = 'INSERT INTO... and the printed variables show that indeed my $array is an Array :
ARRAY1: ArrayL: 2ARRAY2: array . What am I doing wrong here ?
json_decode returns an object, unless you specify you want an array with the second optional argument:
Some other useful advice:
Use var_dump for debugging purposes. It will help you understand the structure of any objects/arrays in your code.
You should not be accepting data through post and the using it in an SQL query without any sanitation, anyways. I highly recommend you fix that asap.