开发者

How to loop through an array of checkboxes and a MySQL database without overlap?

for($j = 0; $j < $length; $j++){
    while($answersRow = mysql_fetch_row($fetch)){
        if($answersRow[0] == $curr_answer_id[$j]){ 

            echo "<input type='checkbox' value='$answersRow[0]' checked>$answersRow[1]</input> ";           
        } else {

            echo "<input type='checkbox' value='$answersRow[0]'>$answersRow[1]</input> ";           
        }
    }
}

Assuming $fetch is my result, here's my d开发者_如何转开发ilemma. The for loop represents the array of checkboxes. The first loop around, everything works fine. However, any more than that, we no longer cycle through the while loop because of the internal mysql pointer. I know I can move the pointer around using mysql_data_seek(), but don't have an idea on how to do so usefully. If I move it back to 0, then it just outputs everything for as many things that were checked.

I basically want to traverse through for each question through the database but without any overlap. It is a bit hard to explain so I apologize if I am not explaining this simple problem properly; I'll try and clarify if need be.


You can save the results of your first while in an array:

//> FIRST LOOP
  while($row = mysql_fetch_assoc($query)) {
    $rows[] = $row; //> Saving in the $rows array
    //> All your code from your first loop
  }

//> SECOND LOOP    
  foreach($rows as $v) {
   //> All your code you need for your second loop without any additional query
  }

Also sorry If I misunderstood your question but It is not so clear what you are asking for

Addendum

After reading better your question if I understood correctly you want to achive everything within only one loop. In this case you can save the html you need in the first while like this:

$firstLoop = '';
$secondLoop = '';
while() {
   $firstLoop .= '<option> [...]';    
   $secondLoop .= '<div> [...]';
}

At this point with one loop you have built the html you need and they are in $firstLoop and $secondLoop. This is of course faster then any other solutions

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜