将两个数组中的行插入php中的mysql表 [英] Insert rows from two arrays into mysql table in php
问题描述
我正在尝试将值从两个数组插入表中。我需要将 array1 和 array2 中的相应值作为行插入表中。即,表行看起来像:
I am trying to insert values into table from two arrays. I need to insert corresponding values from array1 and array2 into table as a row. ie, The table row looks like:
value1, array1[0], array2[0] ...
value1, array1[1], array2[1] ...
我尝试了两个foreach循环。但是innerloop内部的值是重复的。
这是我的代码:
I tried doing it with two foreach loop. But the value inside the innerloop is repeating. Here is my code:
<?php
$servicetype=$_POST['servicetype'];
$serviceamt=$_POST['amount'];
foreach($servicetype as $sertype)
{
foreach($serviceamt as $seramt)
{
$amcinsert2=mysql_query("insert into amc_service_types (amc_service_id,service_type,service_amount) values('$id','$sertype','$seramt')");
break;
}
}
?>
执行此操作时,表将如下所示:
When I execute this, the table will look like:
value1, array1[0], array2[0] ...
value2, array1[1], array2[0] ...
value3, array1[2], array2[0] ...
我不知道应该在哪里我更改代码。谁能帮助我。.
I didn't understand where should I change my code. Can anyone help me..
推荐答案
如果数组都被数字索引并且具有相同的键,则可以像这样遍历它们
If your arrays are both numerically indexed and have the same keys, you can loop over them like this:
for( $i = 0 ; $i < count( $servicetype ) ; $i++ ) {
$amcinsert2=mysql_query("insert into amc_service_types (amc_service_id,service_type,service_amount) values('$id','" . $servicetype[$i] "','" . $serviceamt[$i] . "')");
}
此外,不建议使用mysql_ *函数,应替换它们带有PDO或mysqli_ *函数。
Also, mysql_* functions are deprecated, you should replace them with either PDO or mysqli_* functions.
这篇关于将两个数组中的行插入php中的mysql表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!