Jump to content

How to store array to MySQL


soundsticks

Recommended Posts

I get the result from the other website and make it as array. And the output result like this, how can I store the result by each row to each field in the MySQL?

 

 

Array

(
    [0] => Array
        (
            [0] => 0148
            [1] => 5596
            [2] => 9358
            [3] => 0795
            [4] => 3729
        )
)

 

Link to comment
https://forums.phpfreaks.com/topic/279295-how-to-store-array-to-mysql/
Share on other sites

There are many different ways to do it.

 

An easy one is to serialize the array into string and save it into database. To fetch the data again you will use the unserialize method.

 

Example
$array_to_string = serialize($your_array);

 

you can add the $array_to_string into a column now (column must be in TEXT)

 

to fetch the data from the column

$string_to_array = unserialize($column_array);

If you're trying to store an array to MySQL, chances are you're doing it wrong, and your database schema is incorrect. If you'd like to tell us your schema and what you're trying to do, we may be able to suggest a different schema and how to leverage it.

I get the result from the other website and make it as array. And the output result like this, how can I store the result by each row to each field in the MySQL?

Well you say by each row to each field, so I'm making an assumption about how to insert the data.  If you're not using prepared statements etc. then you need to check/escape the data. Here's an example:

foreach($array as $row) {
   $values = implode(',', $row);
   // INSERT INTO tbl_name (col1,col2,col3,col4,col5) VALUES($values);
}

Storing arrays - each value should be in a row of its own with an id link to a parent table

INSERT INTO tablename (col) VALUES ('val1, val2, val3')                 WRONG

INSERT INTO tablename (col1, col2, col3) (val1, val2, val3)             WRONG

INSERT INTO tablename (id, col) VALUES (id,val1),(id,val2),(id,val3)    RIGHT

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.