0

这是一个数组print_r($_POST)

Array
(
    [january] => Array
        (
            [0] => 10
            [1] => 20
            [2] => 5
        )

    [february] => Array
        (
            [0] => 9
            [1] => 8
            [2] => 10
        )

    [march] => Array
        (
            [0] => 2
            [1] => 5
            [2] => 6
        )

)

循环为$_POST.

$data = array();
foreach ($_POST as $key => $value) {
   $data[] = $value;
}

陈述

INSERT INTO table (january,february,march) VALUES (".implode(", ", $data).")

使用这个当前数组,我该如何做出正确的陈述?我想存储这样的数据

id january february march
--------------------------
1  10      9        2
2  20      8        5
3  5       10       6
4

2 回答 2

3

像这样做:

$month = array("january" => array(10, 20, 5), "february" => array(1,2,3), "march" => array(3,4,5));

$datasets = array();

foreach ($month as $monthname => $monthdata)
{
    foreach ($monthdata as $i => $data)
    {
        $datasets[$i][] = intval($data);
    }
}

$values = array();

foreach ($datasets as $dataset)
{
    $values[] = "(" . implode(", ", $dataset) . ")";
}


echo "INSERT INTO table (january,february,march) VALUES " . implode(", ", $values);

intval在代码中添加了一个应用一些“基本安全性”的代码,因为您永远不应该在数据库中插入未经过滤的用户数据。请告知自己准备好的语句和 mysql 转义;)。

于 2012-11-14T00:18:52.867 回答
-1

这就是我要做的:

$rows=sizeof($_POST['january']);#find how many rows we want to add
for($i=0;$i<$rows;$i++){
  $columns=array();
  $values=array();
  foreach ($_POST as $key => $value) {
    $columns[]=$key;
    $values[]=$value;
  }
  $sql="INSERT INTO table (".implode(",",$columns).") VALUES (".implode(",",$values).")"
  mysql_query($sql)
}
于 2012-11-14T00:21:30.770 回答