I want to make a quiz in PHP. The answers are chosen from radio buttons. If the user chooses the correct answer his score adds 1 if wrong answer his score is reduced by 1. Finally I want his score to appear as an alert.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Quiz</title>
</head>
<body>
<?php
$score=0;
?>
<p><font size="3"> <b>There is 2 multiple choice questions<br />
Every correct answer +1 <br />
Wrong answer -1<br />
Good Luck!</b></font></p></br></br></br>
<table width="300" border="1" cellspacing="2" cellpadding="2">
<tr>
<td><p><font size="3"> <b> Question 1:
</b></font></p>
Guess The Star Of The Movie <font color="red">"The Equalizer"</font><br />
<br />
<input type="radio" name="n1" value="Denzel Washington">Denzel Washington<br>
<input type="radio" name="n1" value="Mark Wahlberg">Mark Wahlberg<br>
<input type="radio" name="n1" value="Jason Statham">Jason Statham<br>
<input type="radio" name="n1" value="Sylvester Stallone">Sylvester Stallone<br>
</form ></td>
</tr>
<tr>
<td><p><font size="3"> <b> Question 2:
</b></font></p>
Guess The Star Of The Movie <font color="red">"Game Plan"</font><br />
<br />
<input type="radio" name="n2" value="Vin Diesel">Vin Diesel<br>
<input type="radio" name="n2" value="Dwayne Johnson">Dwayne Johnson<br>
<input type="radio" name="n2" value="Liam Hamworth">Liam Hamworth<br>
<input type="radio" name="n2" value="Adam Sandler">Adam Sandler<br>
</form ></td>
</tr>
</table>
<?php
$score=0;
if($n1=="Denzel Washington")
$score = $score+1;
else $score = $score-1;
if($n2=="Dwayne Johnson")
$score = $score+1;
else
$score = $score-1;
?>
<button type="button" onclick="alert('<?php echo "your score is: ".$score.""; ?> ')">Submit</button>
</body>
</html>
When I click the submit button the score is -2 although I have chosen the correct answer
Your code is running unconditionally, EVERY time the page is loaded. That means your "is this answer right" code always declares it wrong. so effectively you've got:
$score = 0;
$score = $score - 1; // $n1 is blank, therefore wrong
$score = $score - 1; // $n2 is blank, therefore wrong
You should at LEAST be detecting if the form was actually submitted, e.g.
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
... do scoring here ..
}
But most of that's irrelevant anyways. You don't even have a <form>
tag, so there's no way for those input fields to ever submit to anything.