Reputation: 227
Here is an array from the 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
)
)
Loop for $_POST
.
$data = array();
foreach ($_POST as $key => $value) {
$data[] = $value;
}
Statement
INSERT INTO table (january,february,march) VALUES (".implode(", ", $data).")
With this current array how do I make a correct statement? I want to store the data something like this
id january february march
--------------------------
1 10 9 2
2 20 8 5
3 5 10 6
Upvotes: 0
Views: 1081
Reputation: 4108
This is what I would do:
$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)
}
Upvotes: -1
Reputation: 5351
Do it like this:
$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);
I have put an intval
in the code to apply some "basic security" because you should never insert users data unfiltered in your database. Inform yourself about prepared statements and mysql escaping, please ;).
Upvotes: 3