简体   繁体   中英

How to insert this data to mysql php

Array
(
    [id] => Array
        (
            [0] => 1
            [1] => 1
            [2] => 1
        )

    [kind] => Array
        (
            [0] => 1
            [1] => 2
            [2] => 3
        )

    [qty] => Array
        (
            [0] => 123
            [1] => 456
            [2] => 789
        )

)

This is how my data look like.Here is my insert 1 row code

function insert($table, $array_data)
{
    $key = array();
    $value = array();
    foreach($array_data as $v=>$row){
        $key[] = $v;
        $value[] = "'".$row."'";
    }
    $data_key = implode(',', $key);
    $data_value = implode(',', $value);

    $sql = "INSERT INTO ".$table."(".$data_key.") VALUES (".$data_value.")";
    $this->setQuery($sql);
    $this->query();
}

Please help me make a function to insert multi rows somethings like

function insert_multi($table, $array_data)
{
    ...

    $sql = "INSERT INTO ".$table."(".$data_key.") VALUES (".$data_value1."), (".$data_value2.")";
    $this->setQuery($sql);
    $this->query();
}

I'm trying many ways but only return empty value or "Array" string. My point is make those value turn into this INSERT INTO table (id, kind, qty) VALUES (1, v2, v3), (1, v2.1, v3.1),...
Many thanks! ^^

Guess you want something like this:

function insert_multi($table, $array_data)
{
    $sql = "INSERT INTO " . $table . " (" . implode(',', array_keys($array_data)) . ") VALUES ";
    $rows = [];
    $columns = array_keys($array_data);
    for ($ii = 0; $ii < count($array_data[$columns[0]]); $ii++) {
        $values = [];
        foreach ($columns as $column) {
            $values [] = $array_data[$column][$ii];
        }
        $rows [] = "('" . implode("','", $values) . "')";
    }
    $sql .= implode(',', $rows);

    $this->setQuery($sql);
    $this->query();
}

but brace yourself for SQL injections when building queries that way...

Hope this will help you. Not tested so make changes if there is any syntax error. you need to just generate a string like (val1,val2),(val3,val3)

function them($table, $array_data)
{

    ...
    $keys = array_keys($array_data);
    $length = count($array_data[$keys[0]]);
    $sql = '';
    for ($i=0;$i < $length;$i++)
    {
        $sql .= "('";
        foreach($keys as $index => $key){
           $sql .= $array_data[$key][$i];
           if($index < count($keys)-1)
             $sql .= ",";
        }
        $sql .= "')";
        // if there is another array member, add a comma
        if( $i < $length-1 )
        {
            $sql .= ",";
        }
    }

    $sql = "INSERT INTO ".$table."(".implode(',',$keys).") VALUES ".$sql;
    $this->setQuery($sql);
    $this->query();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM