如何在INSERT中做一个foreach?

时间:2016-06-16 07:12:27

标签: php mysql foreach insert

当我向mysql输入数据时,它显示如下图像,我想将所有数据带到一行,而不是像下面的图像那样在很多行中。但由于我使用数组输入数据,我只能同时访问一个元素。那么如何将数据输入到一行?下面是我的代码片段和表格中的一个片段,非常感谢。

$array = array("AAPL","GOOG","YHOO","FB","MSFT","NKE","SBUX");

foreach ($array as $s) {
    $sss="PR".$s
    $amount=//some value from $_POST
    $value=//some value from $_POST

    $sql = "INSERT INTO portfolio ({$s} , {$sss}) VALUES ('{$amount}', '{$value}')";
}

从MYSQL表中剪切 enter image description here

3 个答案:

答案 0 :(得分:1)

您可以先将这些“PR ..”列添加到数组中,然后使用implode()构建您的into子句。

$array = array("AAPL","GOOG","YHOO","FB","MSFT","NKE","SBUX");
$amount = 'dunno';
$value = 'something';
foreach ($array as $s) {
    $array[] = "PR" . $s;
}
$sql = 'INSERT INTO portfolio (' . implode(',', $array) . ') 
            VALUES ("' .$amount . '", "' . $value . '")';
echo $sql; // INSERT INTO portfolio (AAPL,GOOG,YHOO,FB,MSFT,NKE,SBUX,PRAAPL,PRGOOG,PRYHOO,PRFB,PRMSFT,PRNKE,PRSBUX) VALUES ("dunno", "something")
exit;

无法构建完整查询,因为您没有指定$ amount和$ value的数据类型。

答案 1 :(得分:0)

$array = array("AAPL","GOOG","YHOO","FB","MSFT","NKE","SBUX");
$keys = array();
$values = array();
foreach ($array as $s) {
$sss="PR".$s;
$amount=//some value from $_POST
$value=//some value from $_POST
$keys[] = "`{$sss}`";
$keys[] = "`{$s}`";
$values[] = "'{$value}'";
$values[] = "'{$amount}'";
}
$query = "INSERT INTO 'portfolio' (" . implode(",", $keys) . ")     VALUES (" . implode(",", $values. ");";

答案 2 :(得分:0)

只需将insert语句放在for循环旁边

   $array = array("AAPL","GOOG","YHOO","FB","MSFT","NKE","SBUX");
    $sss='';$amount='';$value='';
    foreach ($array as $s) {
        $sss.=$s.",PR".$s.',';
        $amount.= "'VALUE for WITHOUT PR','VALUE for WITH PR',";
        $value.="'VALUE for WITHOUT PR','VALUE for WITH PR',";//some value from $_POST
    }
    $sss = rtrim($sss,',');
    $amount = rtrim($amount,',');
    $value = rtrim($value,',');
    echo $sql = "INSERT INTO portfolio ( {$sss}) VALUES ({$amount}, {$value})";