0

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] ...

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..

2
  • use for loop instead Commented Nov 4, 2014 at 10:01
  • if you want to repeat VALUE1 everytime, you must insert it statically, but why array2 is giving wrong result i dont know.... Commented Nov 4, 2014 at 10:05

2 Answers 2

1

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] . "')");

}

Also, mysql_* functions are deprecated, you should replace them with either PDO or mysqli_* functions.

Sign up to request clarification or add additional context in comments.

Comments

1

at the begining you have to make sure you have the same size of both arrays, actually what you are doing will add n*n combinations to the mysql , and not what you wanna do ,the break will escape the for loop from the first run which is anyway is gonna be the first array[0], so try to do like this :

<?php
$servicetype=$_POST['servicetype'];
$serviceamt=$_POST['amount'];
var i=0;
foreach($servicetype as $sertype)
{
$amcinsert2=mysql_query("insert into amc_service_types (amc_service_id,service_type,service_amount) values('$id','$sertype','$serviceamt[$i]')");
$i++;  
}
?>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.