Jump to content

nested foreach loop problem


wayz1229

Recommended Posts

i need help with the code below.. the code does not get correct qid from table questions.

 

let say i enter 2 qtitle, and each qtitle has 3 atitle..

but once the data entered in database..

 

the error is like below:

 

(qid=1)qtitle1- i get 6 atitle (by right should be 3 atitle)

 

(qid=2)qtitle2- i get 12 atitle (by right should be 3 atitle)

 

anyone can help me to solve this problem.. i realy need some help.. the error is on the coding below..

 

<?php
foreach ($_POST['questions'] as $q) {
        if (trim($q) != '') {
            $qtitles[] = $q;
        }
    }

foreach ($qtitles as $qtitle) {
        $query = "INSERT INTO questions (qtitle) VALUES ('$qtitle')";
        $result = mysql_query($query) or die("ERROR: $query. ".mysql_error());

    $qid = mysql_insert_id();

    unset($query);
    unset ($result);


foreach ($_POST['options'] as $o) {
        if (trim($o) != '') {
            $atitles[] = $o;
        }
    }

    foreach ($atitles as $atitle) {
        $query = "INSERT INTO answers (qid, atitle, acount) VALUES ('$qid', '$atitle', '0')";
        $result = mysql_query($query) or die("ERROR: $query. ".mysql_error());
    }
}
?>

 

Link to comment
https://forums.phpfreaks.com/topic/180744-nested-foreach-loop-problem/
Share on other sites

the atitles from the first loop are remaining the second loop.

you need to unset the $atitles array

i.e.

<?php
foreach ($_POST['questions'] as $q) {
        if (trim($q) != '') {
            $qtitles[] = $q;
        }
    }
   
foreach ($qtitles as $qtitle) {
        $query = "INSERT INTO questions (qtitle) VALUES ('$qtitle')";
        $result = mysql_query($query) or die("ERROR: $query. ".mysql_error());
   
    $qid = mysql_insert_id();

    unset($query);
    unset ($result);

unset($atitles);
foreach ($_POST['options'] as $o) {
        if (trim($o) != '') {
            $atitles[] = $o;
        }
    }

    foreach ($atitles as $atitle) {
        $query = "INSERT INTO answers (qid, atitle, acount) VALUES ('$qid', '$atitle', '0')";
        $result = mysql_query($query) or die("ERROR: $query. ".mysql_error());
    }
}
?>

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.