inserting data from nested arrays into mysql using php

sauutmhj  于 2022-10-22  发布在  Mysql
关注(0)|答案(3)|浏览(119)

i have this nested array of json data and i am trying to insert specific data into the MYSQL database. However im getting an error and i simply don't know what is wrong with my code. Sorry still new to php/mysql. Any help is appreciated
Here is the json array:

  1. [
  2. {
  3. "title": "★ (Blackstar)",
  4. "artist": "David Bowie",
  5. "year": "2016",
  6. "genre": "Jazz",
  7. "media": [
  8. {
  9. "totalDiscs": "1",
  10. "position": "1",
  11. "tracks": [
  12. {
  13. "title": "★ (Blackstar)",
  14. "number": "1",
  15. "artists": []
  16. },
  17. {
  18. "title": "'Tis A Pity She Was A Whore",
  19. "number": "2",
  20. "artists": []
  21. },
  22. {
  23. "title": "Lazarus",
  24. "number": "3",
  25. "artists": []
  26. },
  27. {
  28. "title": "Sue (Or In A Season Of Crime)",
  29. "number": "4",
  30. "artists": []
  31. },
  32. {
  33. "title": "Girl Loves Me",
  34. "number": "5",
  35. "artists": []
  36. },
  37. {
  38. "title": "Dollar Days",
  39. "number": "6",
  40. "artists": []
  41. },
  42. {
  43. "title": "I Can't Give Everything Away",
  44. "number": "7",
  45. "artists": []
  46. }
  47. ]
  48. }
  49. ],
  50. "score": 1
  51. }
  52. ]

Here is my code:

  1. $json = json_decode($result, true);
  2. $servername = "localhost";
  3. $username = "root";
  4. $password = "";
  5. $dbname = "4tracks";
  6. // Create connection
  7. $conn = new mysqli($servername, $username, $password, $dbname);
  8. // Check connection
  9. if ($conn->connect_error) {
  10. die("Connection failed: " . $conn->connect_error);
  11. } else {
  12. //echo "connected <br/>";
  13. }
  14. $sql = "INSERT INTO tracks (artist_name)
  15. VALUES ('".$json[0]['artist']."')";
  16. if (array_key_exists('genre',$json[0])){
  17. $sql = "INSERT INTO tracks (track_genre)
  18. VALUES ('".$json[0]['genre']."')";
  19. }
  20. foreach($json[0]['media'] as $key => $values){
  21. foreach($values['tracks'] as $key1 => $values1) {
  22. $sql .= "INSERT INTO tracks (track_name)
  23. VALUES ('".$values1['title']."')";
  24. }
  25. }
  26. if ($conn->query($sql) === TRUE) {
  27. echo "New record created successfully";
  28. } else {
  29. echo "Error: " . $sql . "<br>" . $conn->error;
  30. }
  31. $conn->close();

Here is the output when i run the .php on wamp:
Error: INSERT INTO tracks (artist_name) VALUES ('David Bowie'); INSERT INTO tracks (track_genre) VALUES ('Jazz');
INSERT INTO tracks (track_name) VALUES ('★ (Blackstar)');
INSERT INTO tracks (track_name) VALUES (''Tis A Pity She Was A Whore');
INSERT INTO tracks (track_name) VALUES ('Lazarus');
INSERT INTO tracks (track_name) VALUES ('Sue (Or In A Season Of Crime)');
INSERT INTO tracks (track_name) VALUES ('Girl Loves Me');
INSERT INTO tracks (track_name) VALUES ('Dollar Days');
INSERT INTO tracks (track_name) VALUES ('I Can't Give Everything Away');
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'INSERT INTO tracks (track_genre) VALUES ('Jazz');INSERT INTO tracks (track_n' at line 2---

q43xntqr

q43xntqr1#

The most obvious issue is that you are building one string with multiple queries in it. While executing multiple queries is possible using mysqli_ it is not done using the ->query() method, and would be simpler to execute each query independantly.
Also you are writing one query per column in the tracks table, when you can INSERT multiple columns to a table at the same time in one query.
Then you will need to loop around your JSONdata structure using a number of loops, the foreach loop is best for this purpose.
Also if you use parameterized queries, the issues of quotes in a string like "title": "'Tis A Pity She Was A Whore" will automatically be taken care of for your.
So I suggest this as a solution

  1. <?php
  2. $servername = "localhost";
  3. $username = "root";
  4. $password = "";
  5. $dbname = "4tracks";
  6. // Create connection
  7. $conn = new mysqli($servername, $username, $password, $dbname);
  8. // Check connection
  9. if ($conn->connect_error) {
  10. echo "Connection failed: " . $conn->connect_error;
  11. exit;
  12. }
  13. $j = file_get_contents('tst.json');
  14. $json = json_decode($j);
  15. if (json_last_error() != 0) {
  16. echo json_last_error_msg();
  17. }
  18. // Notice we prepare the query ONCE, but later execute it many times
  19. // with different data in the parameters
  20. $sql = "INSERT INTO tracks (artist_name, track_genre, track_name) VALUES (?,?,?)";
  21. $stmt = $conn->prepare($sql);
  22. // check the prepare worked, if not report errors and exit
  23. if (! $stmt) {
  24. echo $conn->error;
  25. exit;
  26. }
  27. // bind the variables names to the ? place holders
  28. // the variables at this point do not have to exists, or have data in them
  29. $stmt->bind_param('sss', $artist, $genre, $title);
  30. foreach($json as $cd) {
  31. foreach($cd->media as $media) {
  32. foreach($media->tracks as $track){
  33. // load the bound variables with the data for this insert execution
  34. $artist = $cd->artist;
  35. $genre = $cd->genre;
  36. $title = $track->title;
  37. $result = $stmt->execute();
  38. // check the insert worked, if not report error
  39. if (!$result) {
  40. echo $conn->error;
  41. exit;
  42. }
  43. }
  44. }
  45. }
展开查看全部
xytpbqjk

xytpbqjk2#

  1. INSERT INTO tracks (track_name) VALUES (''Tis A Pity She Was A Whore');

The 'Tis - you need to escape that single quote.

  1. $sql = "INSERT INTO tracks (artist_name)
  2. VALUES ('". addslashes ($json[0]['artist']) ."');";
ergxz8rk

ergxz8rk3#

Escaping will make sure no special symbols (like the " symbols in JSON) will be parsed by MySQL.
To escape your query, use $mysqli->real_escape_string($my_json); .
Always escape whatever you try to insert into a database. Or even better - use parameterized or prepared statements (read more here ).

相关问题