以下是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
答案 0 :(得分: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转义,请;)。
答案 1 :(得分:-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)
}