Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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.

share|improve this question

2 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

share|improve this answer
correct the first $row['PRICE'] to $row['ID'] and get an up-vote as reward ;) – maggie Oct 18 '10 at 15:04
thanks @maggie , i see it and correct it. – Haim Evgi Oct 18 '10 at 15:09
@HaimEvgi Haim, I think you should change mysql_real_query function which isn't available in php anymore. – Oğuz Çelikdemir Nov 29 '12 at 8:39

You can try this code (quick 'n' dirty):

foreach($product_array as $v) {
  $query = 'insert into tablename values (null, \'' . $v['id'] . '\', \'' . $v['name'] . '\', ' . $v['price'] . ');'
  mysql_query($query);
}
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.