如何使用php在phpmyadmin中插入数组数组

时间:2016-04-14 09:53:19

标签: php mysql arrays

我正在尝试在数据库中插入一个行数组,并且每行数组包含另外三行。

foreach($type as $a=>$b)
    {
     $sql="INSERT INTO `actual_regular` (`employee`, `sex`, `caste`, `family`, `local`, `worked_month`, `incash`, `total_salary`) VALUES ('$type[$a]', '$sex_actual[$a]', '$caste_actual[$a]', '$family_actual[$a]', '$employee_actual[$a]', '$worked_month[$a]', '$cash_actual[$a]', '$salary_actual[$a]');";
mysql_query($sql); 

上面会插入行数组。每行包含3行,将插入新表

$insert = "INSERT INTO `more_regular` (`product_detail`, `unit`, `quantity`, `price`) VALUES ('$detail_product[0]', '$unit[0]', '$quantity[0]', '$price[0]');";
     $insert = "INSERT INTO `more_regular` (`product_detail`, `unit`, `quantity`, `price`) VALUES ( '$detail_product[1]', '$unit[1]', '$quantity[1]', '$price[1]');";
     $insert = "INSERT INTO `more_regular` (`product_detail`, `unit`, `quantity`, `price`) VALUES ('$detail_product[2]', '$unit[2]', '$quantity[2]', '$price[2]');";        
mysql_query($insert); 
} // above foreach ends here

我的意思是需要在表actual_regular中插入多行,每行包含3行。这3行插入表more_regular

1 个答案:

答案 0 :(得分:1)

对单个插入操作使用单个插入查询,如下所示:

<?php
$insert = "INSERT INTO `more_regular` (`product_detail`, `unit`, `quantity`, `price`) VALUES ";
$values = array();
foreach ($type as $a=>$b) {
    $values[] = "('$detail_product[0]', '$unit[0]', '$quantity[0]', '$price[0]')";
    $values[] = " ( '$detail_product[1]', '$unit[1]', '$quantity[1]', '$price[1]')";
    $values[] = " ('$detail_product[2]', '$unit[2]', '$quantity[2]', '$price[2]')";
} // above foreach ends here
if (! empty($values)) {
    $insert .= implode(', ', $values);
}
mysql_query($insert);
?>

基本上,逻辑是:

INSERT INTO TABLE (ID, NAME) VALUES
(1,'Andrew'),
(2,'Glenn'),
(3,'Marvel');