I’m new to PHP so I am in need of your help.
My table in web is in a loop so it gets values in my mySQL phpMyAdmin database until it reaches the end of the database table.
I have a problem getting the desired value I want to show up in my table when certain button is pressed. Once I pressed a single button, it actually shows up the value of it, BUT, IT SHOWS THE OTHER BUTTON’S VALUE AS WELL.
In my conclusion, I think my $_POST code is missing something or is a complete mistake.
The code is here:
<tr>
<?php
while($row = mysqli_fetch_assoc($query)){
$exerciseid = $row['exerciseid'];
$question = $row['question'];
$a = $row['answera'];
$b = $row['answerb'];
$c = $row['answerc'];
$correctanswer = $row['answer'];
?>
</tr>
<tr>
<td><?php echo $question?></td>
<td><button class="btn btn-primary" value="<?php echo $a?>" name="a-submit">A. <?php echo $a?></button></td>
<td><button class="btn btn-primary" value="<?php echo $b?>" name="b-submit">B. <?php echo $b?></button></td>
<td><button class="btn btn-primary" value="<?php echo $c?>" name="c-submit">C. <?php echo $c?></button></td>
<td><?php
if($_SERVER['REQUEST_METHOD'] === 'POST'){
if(isset($_POST['a-submit'])){
echo $a;
}
else if(isset($_POST['b-submit'])){
echo $b;
}
else if(isset($_POST['c-submit'])){
echo $c;
}
else{
}
}
?>
</td>
</tr>
<?php
}
?>
What do you think is the possible cause of my mistake? Please help
2
Answers
If I am not wrong, all your buttons are in single form that’s why you are getting all the buttons value when you click any button.
I am not sure why you need post here because, if you want to get the button value you can simply get it using jQuery.
Check my sample code.
class “
btn-answer
” -> global class for all answer buttons to call jquery click actionrel
-> to identify the questionquestion<?php echo $i; ?>-answ
-> to identify the answer block the show the user selectionIf you still want to use the same variable name within a loop, and display the value that was submitted by user, you could do it like below :
But this will not prevent multiple answer from being shown because no unique id been given on each variable (for example if there are question which having the same answer).