Alex Alex - 4 months ago 13
JSON Question

Php Cant insert Json data with apostrophe to database

I have some json data that i am retrieving from an external url. I am storing the data but It seems that the values that have an apostrophe "Tes't2" is being skipped over. I have seen people say to quote escape this, but i am not sure how to do this. I'm a noobie. Thanks!

Here is my php

$filename = "http://www.someurl.com/data.json";
$data = file_get_contents($filename);
$array = json_decode($data, true);

foreach($array as $row)
{
$sql = "INSERT INTO table_popular_items(rank, name) VALUES (
'".$row["rank"]."',
'".$row["name"]."'
)";
mysqli_query($connect, $sql);
}


Here is the data.json

[
{
"rank": 1,
"name": "Test1"
},
{
"rank": 2,
"name": "Tes't2"

},
{
"rank": 3,
"name": "Test3"
}


]

Answer

Try this:

 $sql = "INSERT INTO `table_popular_items`(`rank`, `name`) VALUES (
  '".$row["rank"]."', 
  '".addslash($row["name"])."'
  )";