Alex
Alex

Reputation: 17

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"
    }

]

Upvotes: 1

Views: 1372

Answers (2)

Amazone
Amazone

Reputation: 436

Try this:

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

Upvotes: 1

Awlad Liton
Awlad Liton

Reputation: 9351

use mysqli_real_escape_string($con, $YOUR_VARIABLE); should work.

Doc: http://php.net/manual/en/mysqli.real-escape-string.php

Upvotes: 0

Related Questions