Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

insert php array into mysql

Tags:

arrays

php

mysql

I have an array $product_array, and when I use print_r($product_array);. The array shows like this

Array
(
    [0] => Array
        (
            [ID] => P00100
            [NAME] => Edina
            [PRICE] => $20.00
        )

    [1] => Array
        (
            [ID] => P00101
            [NAME] => Richfield
            [PRICE] => $21.00
        )

    [2] => Array
        (
            [ID] => P00102
            [NAME] => Bloomington
            [PRICE] => $22.00
        )
)

I set my database table in 4 columes, first one is mainid, and which is auto increment, following with ID, NAME, PRICE, as the keys showed above. I would like to insert this array $product_array into mysql. Can anyone help? Would be very much appreciated! tks.

like image 701
Tony Shih Avatar asked Oct 18 '10 14:10

Tony Shih


People also ask

How can we store values to array from MySQL database in PHP?

Pass the array in the serialize() method and pass the serialized values in the INSERT query. unserialize([Serialized value]); Fetch records and pass the serialized value in the unserialize() method to convert it to Array format.

What is Array_push in PHP?

Definition and Usage. The array_push() function inserts one or more elements to the end of an array. Tip: You can add one value, or as many as you like. Note: Even if your array has string keys, your added elements will always have numeric keys (See example below).

How can I insert multiple rows in SQL using single query in PHP?

Inserting Multiple Rows into a Table. One can also insert multiple rows into a table with a single insert query at once. To do this, include multiple lists of column values within the INSERT INTO statement, where column values for each row must be enclosed within parentheses and separated by a comma.


1 Answers

   $sql = array(); 
    foreach( $myarray as $row ) {
        $sql[] = '('.$row['ID'].', "'.mysql_real_escape_string($row['NAME']).'",
 "'.$row['PRICE'].'")';
    }
    mysql_query('INSERT INTO table (ID, NAME,PRICE) VALUES '.implode(',', $sql));

see more details :

insert multiple rows via a php array into mysql

like image 156
Haim Evgi Avatar answered Sep 23 '22 20:09

Haim Evgi