1

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

1
  • @MartyWallace I know I should be using PDO...thanks Commented May 23, 2013 at 3:31

1 Answer 1

3

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());
}
Sign up to request clarification or add additional context in comments.

4 Comments

+1 for being able to understand that horribly spaghetti code.
Thanks for helping CORRUPT...You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 1
@PeterBrowne in first version I have a typ0: $inserted_ids were $insert_ids :( Is current version causing error too?
You're a superstar CORRUPT! Many thanks for your quick solution and understanding about my horribly spaghetti code...

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.