Reputation: 4304
I have a foreach loop which completes multiple inserts.
if ($action == '2'){
foreach(array_combine($test_results, $reference_intervals) as $test_result => $reference_interval){
$query = "INSERT INTO model_lab_test_results (model_lab_test_results_pk, case_fk, level, lab_test_fk, result, reference_interval, created, created_by) VALUES ('', '$case_pk', '$level', '$lab_test_pk', '$test_result', '$reference_interval', NOW(), '$author_pk')";
$result = mysql_query($query, $connection) or die(mysql_error());
$inserted_ids[] = mysql_insert_id();
}
Then I run another foreach loop updating each of the records inserted.
if($result){
foreach($lab_tests_pk as $lab_test_pk){
$query_update_results = "UPDATE model_lab_test_results SET lab_test_fk = '$lab_test_pk' WHERE model_lab_test_results_pk IN (" . implode(",", $inserted_ids) . ")";
$result_update_results = mysql_query($query_update_results, $connection) or die(mysql_error());
}
The problem is that each of the four inserted records in array $inserted_ids:
Array ( [0] => 153 [1] => 154 [2] => 155 [3] => 156 )
is updated with the same last value in the array $lab_tests_pk, ie 1776:
Array ( [0] => 2249 [1] => 1349 [2] => 1126 [3] => 1776 )
How can I get each inserted record to be updated with seperate values from $lab_tests_pk?
I know I should be using PDO...thanks...
Upvotes: 1
Views: 255
Reputation: 12168
You might need to use a key for $inserted_ids
too. In you case you just overwrite all recods with each value. All for update to each one. So you only see the last. Try this:
foreach($lab_tests_pk as $key => $lab_test_pk){
$query_update_results = "UPDATE model_lab_test_results SET lab_test_fk = '{$lab_test_pk}' WHERE model_lab_test_results_pk = {$inserted_ids[$key]}";
$result_update_results = mysql_query($query_update_results, $connection) or die(mysql_error());
}
Upvotes: 3