Saving JSON string in MySQL database

I have a JSON string with me

{"name":"jack","school":"colorado state","city":"NJ","id":null} 

I need it to be saved in the database. How can i do this?

My PHP code (I just established a connection to MySQL, but I can not save the entries)

  <?php // the MySQL Connection mysql_connect("localhost", "username", "pwd") or die(mysql_error()); mysql_select_db("studentdatabase") or die(mysql_error()); // Insert statement mysql_query("INSERT INTO student (name, school,city) VALUES(------------------------- ) ") // (How to write this) or die(mysql_error()); echo "Data Inserted or failed"; ?> 
+4
source share
3 answers

We will use json_decode documentation

Also avoid! this is how i will do it below ...

 /* create a connection */ $mysqli = new mysqli("localhost", "root", null, "yourDatabase"); /* check connection */ if (mysqli_connect_errno()) { printf("Connect failed: %s\n", mysqli_connect_error()); exit(); } /* let say we're grabbing this from an HTTP GET or HTTP POST variable called jsonGiven... */ $jsonString = $_REQUEST['jsonGiven']; /* but for the sake of an example let just set the string here */ $jsonString = '{"name":"jack","school":"colorado state","city":"NJ","id":null} '; /* use json_decode to create an array from json */ $jsonArray = json_decode($jsonString, true); /* create a prepared statement */ if ($stmt = $mysqli->prepare('INSERT INTO test131 (name, school, city, id) VALUES (?,?,?,?)')) { /* bind parameters for markers */ $stmt->bind_param("ssss", $jsonArray['name'], $jsonArray['school'], $jsonArray['city'], $jsonArray['id']); /* execute query */ $stmt->execute(); /* close statement */ $stmt->close(); } /* close connection */ $mysqli->close(); 

Hope this helps!

+12
source

Here is an example of help

 <?php $json = '{"name":"jack","school":"colorado state","city":"NJ","id":null}';// You can get it from database,or Request parameter like $_GET,$_POST or $_REQUEST or something :p $json_array = json_decode($json); echo $json_array["name"]; echo $json_array["school"]; echo $json_array["city"]; echo $json_array["id"]; ?> 

Hope this help!

+1
source

Decoding into an array and passing it to mysql_query, the code below does not use mysql_real_escape_string or any other security features that you must implement.

Suppose $ json has {"name": "jack", "school": "colorado state", "city": "NJ", "id": null}

 $json_array = json_decode($json); 

Now you have indexes in the php array, such as: $ json_array ['name']

 mysql_query("INSERT INTO student (name, school,city) VALUES('".$json_array['name']."', '".$json_array['school']."', '".$json_array['city']."') ") or die(mysql_error()); 
0
source

All Articles