从多维数组构建MySQL插入语句

时间:2014-02-09 04:24:13

标签: php mysql arrays multidimensional-array

我需要从一个数组构建INSERT语句但是我被困住这是我到目前为止所做的但显然不对:

INSERT INTO company (, Name, Address, City, State, Zip, Country, Website, NOL
INSERT INTO additionallocations (, CompanyID, Address, City, State, Zip, Country

这是我的数组以及我如何构建语句:

$fieldsArray = array(
                    'company' => array(
                            'Name' => $Name,
                            'Address' => $Address,
                            'City' => $City,
                            'State' => $State,
                            'Zip' => $Zip,
                            'Country' => $Country,
                            'Website' => $Website,
                            'NOL' => $NOL,
                        ),
                    'additionallocations' => array(
                            'CompanyID' => $CompanyID,
                            'Address' => $Address,
                            'City' => $City,
                            'State' => $State,
                            'Zip' => $Zip,
                            'Country' => $Country,
                        )
                    );




        foreach($fieldsArray as $table => $rows) {
            $sql = "INSERT INTO " . $table . " (";
            foreach($rows as $column => $value){
                $sql .= ", " .$column;
            }
        }

        echo $sql;

以下是我最终想要的结果:

INSERT INTO company (Name, Address, City, State, Zip, Country, Website, NOL) VALUES
                             ('$Name', '$Address', '$City', '$State', '$Zip', '$Country', '$Website', '$NOL');

我需要找到一种方法来继续使用VALUES构建它并在开始括号后删除第一个逗号。有人有什么建议吗?

2 个答案:

答案 0 :(得分:2)

foreach($fieldsArray as $table => $rows) 
{
    $sql = "INSERT INTO " . $table . "(";
    foreach($rows as $column => $value)
    {    
         $sql .= $column.", ";
    }
    $sql = rtrim($sql, ", ");
    $sql .= ") VALUES (";

    foreach($rows as $column => $value)
    {    
         $sql .= "'".$value."', ";
    }
    $sql = rtrim($sql, ", ");
    $sql .= ")";
    echo $sql; 
}

答案 1 :(得分:0)

我得到了它的工作:

foreach($fieldsArray as $key => $table){            
    $keys = array_keys($table);
        $values = null;
        $x = 1;

        foreach($keys as $value) {
            $values .= "?";
            if($x < count($keys)) {
                $values .= ', ';
            }
            $x++;
        }

    echo $sql = "INSERT INTO {$key} (`" . implode('`, `', $keys) . "`) VALUES ({$values})" . "<br/>";

}