Reputation: 137
I'm trying to make a self test page where php matches the input with the database and checks if the answer is right. but so far I don't know how to get it to check all the answers individually. the script i got so far only works if all the answers are wrong. How would I do this in PHP?
this is my code so far:
<?php
$host = "localhost";
$user = "root";
$pwd = "";
$db_name = "flashcards";
$link = mysqli_connect($host, $user, $pwd, $db_name)or die("cannot connect");
$sql = mysqli_query($link, "SELECT * FROM Questions ORDER BY ID ASC LIMIT 25") or die(mysqli_error($link));
echo "<form action='".$_SERVER['PHP_SELF']."' method='post'><table border='1'>";
while ($rows = mysqli_fetch_assoc($sql))
{
echo "<tr><td value='".$rows['ID']."'>".$rows['Question']."</td><td><input type='text' name='Answer'></input></td></tr>";
}
echo "</table><input type='submit' name='submit'>test</input></form>";
if (isset($_POST['submit']))
{
if ($_POST['Answer'] != $rows['Answer'])
{
echo "wrong!";
}
else
{
echo "right";
}
}
?>
Upvotes: 0
Views: 213
Reputation: 2009
The problem is here:
<input type='text' name='Answer'></input>
The problem being that all the answer inputs have the same "name", so for each field that you answer, the value (the answer string) gets overwritten.
In order to fix this, you need to get an array of answers, like so:
<input type='text' name='Answer[]'></input>
And then, iterate trough it:
foreach($_POST['Answer'] as $answer)
if (isset($_POST['submit']))
{
if ($answer != $rows['Answer'])
//...
Upvotes: 1