简体   繁体   中英

Insert PHP 3 level array into a database

I am new to database and php and not sure how to do the following. I am using wampserver which comes with mysql.

I am receiving a json data which i used json_decode to get a php 3-level array. Now how do i insert these data into a database and also display it in a table form?

I searched and there are quite a number of examples on insertion portion. But must I create a database with all the fields first before insertion? How to retrieve and display it after insertion?

Sample of the array to be inserted is as shown in another posting: insert from array has multi levels to database using php

I think you should serialize the data and store it in a single column. Use PHP serialize function.

$string = serialize($array);

Now store $string in a text field in DB. You dont need to create different fields for different variables. To retrieve the data from database, you should unserialize the string as:

$array = unserialize($string);

This approach will allow you to save as many variables in DB as you want without need to create separate fields for each variable.

I prefer to use an ORM such as Idiorm/Paris for accessing data in MySQL. It abstracts away the actual query language making it easier and less tedious. Basically you first create your tables in your database and then add/retrieve/remove data using a Model factory class.

<?php

// Our model extension class where MyData is the name of the table
Class MyData extends Model{}

// Create and save a new record
$data = Model::factory('MyData')->create();
$data->id = 1;
$data->somedata = 'important stuff';
$data->save();

// Retrieve a record
$data = Model::factory('MyData')->find_one(1);

?>
<table>
  <tr>
    <td><?php echo $data->somedata; ?></td>
  </tr>
</table>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM