0

I look for examples to solve my problem but im confused. If Ii have a json array like this:

$json = '{"a":"test","b":"test2"},{"a":"test3","b":"test4"}';

//decode to get as php variable
$obj = json_decode($json);

My problem is when i try to insert the values in the database

mysql_query("INSERT INTO suspiciousactivity (ID,Notes)
VALUES ('".$obj->{'a'}."','".$obj->{'b'}."')")or die(mysql_error());

I get this error: duplicate entry for key PRIMARY

How can I insert a multiple values from my JsonArray to my database?

2
  • 2
    Seems to me like you already have a suspiciousactivity entry with ID = test Commented Feb 6, 2013 at 19:13
  • So, you're using results from suspicious activity, and insert it into your database without sanitising? Please change your code, stop using mysql_ functions. They are deprecated and no longer maintained. Your code is very insecure and vulnerable for SQL injection. Commented Feb 6, 2013 at 22:21

1 Answer 1

1

try to use:

$json = '{"a":"test","b":"test2"},{"a":"test3","b":"test4"}';

//decode to get as php variable
$arr = json_decode($json,true); //true to decode as a array not an object

mysql_query("INSERT INTO suspiciousactivity (ID,Notes)
VALUES ('".$arr[0]['a']."','".$arr[0]['b']."')")or die(mysql_error());
//use it as an array.
Sign up to request clarification or add additional context in comments.

3 Comments

sorry, try now. I have changed ´$obj´ for ´$arr´
i try but echo $arr[0]['a']; is empty
sorry i was missin the [] in the $json thanks it works for me

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.