All right, so I am being passed an array of checked items represented by their IDs through a $_GET request. For example, suppose the following form:
Question 1
[ ] Answer 1 [31]
[ ] Answer 2 [32]
[ ] Answer 3 [33]
[ ] Answer 4 [34]
Let's assume the user chose Answer 2
and Answer 4
, so the array that is passed contains 32
and 34
, respectively, symbolizing their IDs in the database. Now, I开发者_StackOverflow社区 want to loop through a database query of ALL of the answers for this question and print back checkboxes. However, if an answer is the one they picked, I'd like to have the checkbox already checked, so that, by my example, the output would be:
Question 1
[ ] Answer 1 [31]
[x] Answer 2 [32]
[ ] Answer 3 [33]
[x] Answer 4 [34]
I guess I'm just a bit off on my looping structure... but here is what I started with:
// The array that gets passed
$curr_answer_id = $_GET['answer'];
$length = count($curr_answer_id);
while($row = mysql_fetch_assoc($fetch2)){
for($j = 0; $j < $length; $j++){
if($row['answer_id'] == $curr_answer_id[$j]){
echo "<input type='checkbox' value='$curr_answer_id[$j]' checked>".$row['answer']."</input>";
} else {
echo "<input type='checkbox' value='$curr_answer_id[$j]'>".$row['answer']."</input>";
}
}
echo "<br \>";
}
However, this duplicates results for as many answers were checked. Aside from the duplicates, however, it functions fine. As in my previous example, the output is:
Question 1
[ ] Answer 1 [31]
[ ] Answer 1 [31]
[x] Answer 2 [32]
[ ] Answer 2 [32]
[ ] Answer 3 [33]
[ ] Answer 3 [33]
[ ] Answer 4 [34]
[x] Answer 4 [34]
How can I fix this using what I've got? If anyone can also lend me to a more efficient way to cycle through all of the data that would be great as well.
Thanks.
Maybe that is the right solution for you?
$curr_answer_id = $_GET['answer'];
while($row = mysql_fetch_assoc($fetch2))
{
echo "<input type='checkbox' value='".$row['answer_id']."' ".(in_array($row['answer_id'], $curr_answer_id) ? " checked" : "").">".$row['answer']."</input>";
echo "<br \>";
}
Not tested.
Update: replaced input value with $row['answer_id']
instead of $curr_answer_id[$j]
The double output is obvious because for each of your resultset from the query, you are running a FOR loop the number of times equal to the number of responses by the user.
while($row = mysql_fetch_assoc($fetch2)){
for($j = 0; $j < $length; $j++){
The WHILE loops through each row (31, 32, 33, 34) and the FOR loop then loops twice. If you'll send 3 answers in your GET request, you'll see each checkbox appearing 3 times.
A solution might be that inside the WHILE loop, you can use in_array()
to check if $row['answer'] exists in $_GET['answer']. And accordingly decide if to check or uncheck the check-boxes.
Hope that helps.
精彩评论