Reputation: 1440
Couldn't find any solution on this yet, so I'm posting it here.
I have the following code:
<?php
//array: key=> value
$begrippen = array(
"agrarisch" => "jagers en boeren",
"cultuur" => "jagers en boeren",
"jagers-verzamelaars" => "jagers en boeren",
"landbouwsamenleving" => "jagers en boeren",
"burgerschap" => "grieken en romeinen",
"christendom" => "grieken en romeinen",
);
$message1 = 'Goedzo!';
$message2 = 'Fout!';
$random_key = array_rand($begrippen);
$value = $begrippen[$random_key];
echo "Begrip: $random_key <br />";
?>
<form method="POST">
<input type="text" autocomplete="off" name="input1" autofocus>
</form>
<?php
if($_POST['input1'] == $value){
echo "<SCRIPT> alert('$message1'); </SCRIPT>";
}else{
echo "<SCRIPT> alert('$message2'); </SCRIPT>";
};
?>
It takes a random key from my array, takes the value and puts that in $value. When I enter input in my textbox, I want it to compare with $value and let it show a message (good or wrong). Yet something goes wrong and I don't know what because sometimes it says it's good, and sometimes it's wrong (while the answer was correct).
Upvotes: 0
Views: 787
Reputation: 22721
Try this,
You can add hidden field in your form and assign the value to be refer.
<form method="POST">
<input type="text" autocomplete="off" name="input1" autofocus>
<input type="hidden" name="inputref" value="<?php echo $value;?>">
<input type="submit" name="submit" value="Submit">
</form>
in PHP: your condition will be
if(isset($_POST['submit'])){
if($_POST['input1'] == $_POST['inputref']){
... Your code
}
}
Upvotes: 1
Reputation: 2819
I don't know without form
submitting how this will work? So add a button as submit
inside your form
.
You need to do change your logic When POST
request called.
<?php
if($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['check'])){
//array: key=> value
$begrippen = array(
"agrarisch" => "jagers en boeren",
"cultuur" => "jagers en boeren",
"jagers-verzamelaars" => "jagers en boeren",
"landbouwsamenleving" => "jagers en boeren",
"burgerschap" => "grieken en romeinen",
"christendom" => "grieken en romeinen",
);
$message1 = 'Goedzo!';
$message2 = 'Fout!';
$random_key = array_rand($begrippen);
$value = $begrippen[$random_key];
echo "Begrip: $random_key <br />";
if($_POST['input1'] == $value){
echo "<SCRIPT> alert('$message1'); </SCRIPT>";
}else{
echo "<SCRIPT> alert('$message2'); </SCRIPT>";
}
}
?>
<form method="POST">
<input type="text" autocomplete="off" name="input1" autofocus />
<input type="submit" value="Check" name="check" />
</form>
Upvotes: 0