Create a mysql table from a JSON variable

Code, Game programming and artificial intelligence

Simple code piece to create a mysql table and insert values from any JSON variable. This is a fast hack.. check field types etc 🙂 There’s proboally better ways, but this one work and has already saved me hours if manual field-naming

This is can be modified to create a relation table handling objects aswell, now it’s made for array formed JSON stuff and not objects as for example … “providerships”: [{“title”: “Legal”, “is_past”: false,.

 <?php function JSON_to_table($j_obj, $tblName){ $j_obj = json_decode($your_JSON_variable, true); if(!mysql_num_rows( mysql_query("SHOW TABLES LIKE '" . $tblName . "'"))){ $cq = "CREATE TABLE ". $tblName ." ( id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,"; foreach($j_obj as $j_arr_key => $value){ $cq .= $j_arr_key . " VARCHAR(256),"; } $cq = substr_replace($cq,"",-1); $cq .= ")"; mysql_query($cq) or die(mysql_error()); } $qi = "INSERT INTO $tblName ("; reset($j_obj); foreach($j_obj as $j_arr_key => $value){ $qi .= $j_arr_key . ","; } $qi = substr_replace($qi,"",-1)…

View original post 34 more words


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s