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
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);

Link to comment
Share on other sites

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.

Link to comment
Share on other sites

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);
}
Link to comment
Share on other sites

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
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.