-1

I am trying to insert the results from a json array into MySQL using

foreach ($feed->items as $item) {
  $query = "insert into data(id,url,keyword)values ($item->id, $item->url,$item->kind)";
  $result = mysql_query($query);
  echo $result;
}

I have confirmed the database details are OK and the $items are correct.
Can anyone point me in the right direction? I am fairly new to PHP so any help is appreciated.

André Dion
  • 21,269
  • 7
  • 56
  • 60
Kevin Wincott
  • 25
  • 1
  • 6
  • how ur json string look like and for string values need to enclose them with `''` in insert. – Abhik Chakraborty Apr 02 '14 at 11:37
  • Where is end your foreach loop? – Sadikhasan Apr 02 '14 at 11:40
  • Executing SQL queries in homogeneous loop is almost always a bad idea - like in your case. Didn't anyone told you that `INSERT` can be used to insert multiple rows? – ElmoVanKielmo Apr 02 '14 at 11:40
  • Just yourself 1 thing: How should PHP know, if this `values ($item->id, ...` is (part) of a variable, or a string you want to represent? If you have 2 variables, `$item->i` and `$item->id`, how should PHP know the difference?? – Daniel W. Apr 02 '14 at 11:42
  • 1
    @DanFromGermany of course you are right. It can be deducted even from SO code coloring... – ElmoVanKielmo Apr 02 '14 at 11:43

2 Answers2

3

You need to escape the values in the SQL:

$query = "insert into data(id,url,keyword)values ('" . mysql_real_escape_string($item->id) . "', '" . mysql_real_escape_string($item->url) . "' , '". mysql_real_escape_string($item->kind) . "')";
  1. this adds quotation marks ' around the variables so that the SQL can be parsed at all
  2. This prevents SQL injection.
Community
  • 1
  • 1
akirk
  • 6,757
  • 2
  • 34
  • 57
0

You need to wrap your variabels in your query :

$query = "insert into data(id,url,keyword)values ('{$item->id}', '{$item->url}', '{$item->kind}')";
Brovoker
  • 896
  • 5
  • 16