php 将php数组插入mysql

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3960398/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 11:34:37  来源:igfitidea点击:

insert php array into mysql

phpmysqlarrays

提问by Tony Shih

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

我有一个数组 $product_array,当我使用 print_r($product_array); 时。数组显示如下

Array
(
    [0] => Array
        (
            [ID] => P00100
            [NAME] => Edina
            [PRICE] => .00
        )

    [1] => Array
        (
            [ID] => P00101
            [NAME] => Richfield
            [PRICE] => .00
        )

    [2] => Array
        (
            [ID] => P00102
            [NAME] => Bloomington
            [PRICE] => .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.

我将数据库表设置为 4 列,第一个是 mainid,它是自动递增的,后面是 ID、NAME、PRICE,如上所示。我想将此数组 $product_array 插入到 mysql 中。任何人都可以帮忙吗?将不胜感激!tks。

回答by Haim Evgi

   $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

通过php数组将多行插入到mysql中

回答by Vasilis Lourdas

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

你可以试试这个代码(快速“n”脏):

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