【问题标题】:How to insert this array to mysql using loop?如何使用循环将此数组插入mysql?
【发布时间】:2014-06-23 00:56:11
【问题描述】:

如何使用循环将这个数组 [$obj] 插入到 mysql 中?

Array
(
    [apple] => Array
        (
            [0] => fruit
            [1] => 15
        )

    [cat] => Array
        (
            [0] => animal
            [1] => 400
        )

    [pumpkin] => Array
        (
            [0] => vegetables
            [1] => 20
        )

    [orange] => Array
        (
            [0] => fruit
            [1] => 30
        )
)

我想使用这样的循环将数组 [$obj] 插入 mysql。

|___id__|___ product__|_____type_____|__price__|
|   1   |     apple   |    fruit     |    15   |
|   2   |     cat     |    animal    |    400  |
|   3   |   pumpkin   |  vegetables  |    20   |
|   4   |    orange   |    fruit     |    30   |

我该怎么做?

谢谢。

【问题讨论】:

    标签: php mysql arrays


    【解决方案1】:
    $sql = "INSERT INTO tableName (product, type, price) VALUES";
    foreach($array as $key => $value)
    {
        $sql += " ('$key', '$value[0]', $value[1]),";
    }
    $sql +=  substr_replace($sql,"",-1). ";";
    //perform your INSERT here.
    

    请务必将 tableName$array 替换为各自的名称

    【讨论】:

    • @Strawberry,是你的意思,还是你的意思是准备好的陈述更好?
    • @AnthonyRaymond: 兄弟你可以使用内爆函数...先把它填入一个数组然后执行内爆函数
    • @Strawberry 做到了,我会替换它
    • @user3598505 什么意思,不工作?你遇到了 MySql 错误吗? php是否返回错误?
    【解决方案2】:

    试试这个 $obj 是你的数组

    $finalarray = array();
    foreach($obj as $main_key=>$main_value)
    {
    $product = $main_key;
    $type = $main_value[0];
    $price = $main_value[1];
    $string = "('','$product','$type','$price')";
    $finalarray[] = $string;
    
    }
    $final_values_array = implode(',',$finalarray);
    mysql_query("INSERT INTO TABLENAME('id','product','type','price') VALUES $final_values_array");
    

    【讨论】:

    • 请问你的数组名是什么
    【解决方案3】:

    试试这个

    $array=Array
    (
        [apple] => Array
            (
                [0] => fruit
                [1] => 15
            )
    
        [cat] => Array
            (
                [0] => animal
                [1] => 400
            )
    
        [pumpkin] => Array
            (
                [0] => vegetables
                [1] => 20
            )
    
        [orange] => Array
            (
                [0] => fruit
                [1] => 30
            )
    )
    $query = "INSERT INTO tableName (product, type, price) VALUES";
    $sub='';
    foreach($array as $key => $value)
    {
        $sub.="('$key', '$value[0]', $value[1]), ";
    }
    $sql = $query . substr_replace($sub,"",-1);
    

    这是批量插入

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-06-19
      • 2019-01-21
      • 2017-12-17
      • 2015-05-11
      • 2018-06-06
      • 2013-04-05
      相关资源
      最近更新 更多