$number1 = mt_rand(1,9);
$number2 = mt_rand(1,9);
$total = $number1 * $number2;
echo "<form method='post'>";
echo $number1 . " x " . $number2 . " = <input type='number' name='num1' required /><br>";
echo "<input type='submit' value='submit!' name='done'>";
echo "</form>";
if (isset($_POST['done'])) {
if (isset($_POST['num1']) == $total) {
echo "Correct!";
} else {
echo "Wrong!";
}
}
It always says Correct! And I dont know why ( im a beginner ), I just want to check if num1 is equal to $total
You have many problems in your code :
you must first check if the post is submit then if its wrong type the form
if (isset($_POST['done'])) {
//your code
}
else {
//your form
}
save $total in session to reuse it when the form submit, in your case $total have different value every time
isset() return true or false you can't comparison true or false with integer value if you want to use isset your code must be like this:
if(isset($_POST['num1']) && $_POST['num1'] == $total) {
}
You're comparing isset($var) to $total. They're both truthy so the condition is always true as long as 'num1' is defined in your POST data.
Maybe you should do something like :
isset($_POST['num1']) && $_POST['num1'] == $total
You should also probably cast 'num1' to a number
As said by Tom Udding, every time you refresh the page it calls ALL of that code again, so number1 and number2 are being randomly selected again.
Your current code has no way of saving the previous variable values. An unconventional way would be to add a hidden form field with the answer to the question, like below:
<?php
if (isset($_POST['done']) && isset($_POST['num1']))
{
//Get answer from form.
$total = $_POST['answer'];
if ($_POST['num1'] == $total)
{
echo "Correct!";
}
else
{
echo "Wrong!";
}
}
$number1 = mt_rand(1, 9);
$number2 = mt_rand(1, 9);
$total = $number1 * $number2;
echo "<form method='post'>";
echo $number1 . " x " . $number2 . " = <input type='number' name='num1' required /><br>";
//Added hidden form with answer.
echo "<input type='number' hidden name='answer' value='$total' />";
echo "<input type='submit' value='submit!' name='done'>";
echo "</form>";
?>
HOWEVER...
In a realistic rich web application, you wouldn't put your answer in your form for users to see, this is where you can use sessions to track your user's information as they traverse (or in your case refresh) your page.
So a more practical answer to your question would be the following:
<?php
session_start();
if (isset($_POST['done']) && isset($_POST['num1']))
{
$answer = $_SESSION['answer'];
if ($_POST['num1'] == $answer)
{
echo "Correct!";
} else
{
echo "Wrong!";
}
}
$number1 = mt_rand(1, 9);
$number2 = mt_rand(1, 9);
$total = $number1 * $number2;
$_SESSION['answer'] = $total;
echo "<form method='post'>";
echo $number1 . " x " . $number2 . " = <input type='number' name='num1' required /><br>";
echo "<input type='number' hidden name='answer' value='$total' />";
echo "<input type='submit' value='submit!' name='done'>";
echo "</form>";
?>
Related
I am learning php atm and i decided to make a simple game but now im confronted with a problem. I have the following code:
<form action="wolf.php" method="POST">
<input type="submit" value="Attack" name="submit"/> <br />
<?php
$hp = 100;
if(isset($_POST['submit'])) {
$attack = $_POST['submit'];
$damage = mt_rand(5, 30);
$newhp = $hp - $damage;
if ($attkdamage = $hp - $damage ) {
echo "Your HP is: ". $newhp . "<br / >";
echo "You took: " . $damage . " damage!";
}
}
?>
As you can see I have a variable with an integer (100) and a simple mt rand. What I want is that after I submit and get a $newhp (100 - the random number), that number to replace $hp. and the next time I submit the button I want the value of $damage to be subtracted from the previous action, so basically to save the $newhp as $hp.
If possible storing this value in a session variable that will be saved in the browser you use, for more information read here $_SESSION
<?php
session_start();
if(!isset($_SESSION["hp"]))
$_SESSION["hp"]=100;
if(isset($_POST['submit'])) {
$attack = $_POST['submit'];
$damage = mt_rand(5, 30);
$newhp = $_SESSION["hp"] - $damage;
if ($attkdamage = $_SESSION["hp"] - $damage ) {
echo "Your HP is: ". $newhp . "<br / >";
echo "You took: " . $damage . " damage!";
}
echo "<pre>previus hp " .$_SESSION["hp"];
$_SESSION["hp"]= $newhp;
echo "next hp " . $_SESSION["hp"]."</pre>";
}
?>
i wanna display check box of weekdays - that display the week checked and the other days not checked
$days = $user->work_days;
$real_days = explode(',', $days);
$week = array('Saturday','Sunday' ,'Monday','Tuesday' ,'Wendnesday' ,'Thursday' ,'Friday');
for ($i = 0; $i < count($week) ; $i++) {
if (count($real_days) <= $i and isset($real_days[$i]) and $real_days[$i] ==$i ) {
echo "<input type='checkbox' name='working_days[]' value='$i' checked >" .$week[$i]." <br>"; }else{
echo "<input type='checkbox' name='working_days[]' value='$i' >".$week[$i]." <br>";
}
}
Here's a solution, btw you should avoid rewriting the same code twice ;)
<?php
$days = 'Monday,Wendnesday';
$real_days = explode(',', $days);
$week = array('Saturday','Sunday' ,'Monday','Tuesday' ,'Wendnesday' ,'Thursday' ,'Friday');
//foreach is more readable
foreach ($week as $dayName) {
$checked = '';
//Check if current week day is in real_days
if (in_array($dayName, $real_days)) {
$checked = ' checked="checked" ';
}
?>
<input type='checkbox' name='working_days[]' <?= $checked ?> ><?= $dayName ?><br>
<?php
}
I'm making a math quiz where the user inputs their answer choice using radio buttons. I want to take the value of the radio button and compare it with the actual answer and increment score if the answer is correct.
At the moment, we are using a submit button at the bottom of the quiz where we are trying to send the data for the "check answers" script. However, I don't think any data is being pulled correctly.
Here is the code for the radio button which is from a form called "mathselect.php"
<?php //php starts here
require("opendbomath.php");
global $link, $DBname ;
if (!empty($_GET)) {
$category = $_GET["category"];
$sql = "SELECT * FROM `math`";
$result = mysqli_query($link,$sql);
$numOfQuestions = "SELECT COUNT(*) FROM `math`";
$queryNumOfQuestions = mysqli_query($link,$numOfQuestions);
if ($queryNumOfQuestions=mysqli_query($link,$sql))
{
// Return the number of rows in database
$rowcount=mysqli_num_rows($queryNumOfQuestions); //this is number of total rows
printf("Result set has %d rows.\n<br><br>",$rowcount);
}
$list = array();
$questionNumber = 0;
while (count($list) < 10){
do { //this is where we pull questions from database
$randomInt = rand(2,$rowcount); //random int is inbetween 2 and numbers of rows
$sqlselect = "SELECT * FROM `math` WHERE `bid` = \"" . $randomInt . "\" AND `acategory` = \"" . $category . "\" ";
$sqlSelectQuery = mysqli_query($link,$sqlselect);
$numOfGoodQuestions = mysqli_num_rows($sqlSelectQuery);
} while ($numOfGoodQuestions == 0); //if it returns blank field, it will loop again
if (in_array($randomInt,$list)){ //if it pulls duplicate number, continue
continue;
}
else {
//use fetch function
$row=mysqli_fetch_array($sqlSelectQuery);
$questionNumber = $questionNumber + 1;
$strQuestionNumber = (string)$questionNumber;
$slots = array();
array_push($slots,$row['aanswer']); //pushes answer choices into slots array
array_push($slots,$row['awrong1']);
array_push($slots,$row['awrong2']);
array_push($slots,$row['awrong3']);
shuffle($slots); //shuffles the answer choices
?>
<form action="mathcheck.php" method="post">
<?php
print ("<input type = 'radio' name='test".$strQuestionNumber."' value ='$slots[0]'>".$slots[0]."<br>"); //displaying 4 radio buttons with value of answer choice
print ("<input type = 'radio' name='test".$strQuestionNumber."' value ='$slots[1]'>".$slots[1]."<br>");
print ("<input type = 'radio' name='test".$strQuestionNumber."' value ='$slots[2]'>".$slots[2]."<br>");
print ("<input type = 'radio' name='test".$strQuestionNumber."' value ='$slots[3]'>".$slots[3]."<br>");
print("<br>");
}
}
//submit buton will go here
?>
<input type ="submit" value = "submit">
</form>
And also, here is the code for the "check answer" script which is called "mathcheck.php"
<?php
include('mathselect.php');
$answerChoice1 = $_POST('test1'); //pulls value of radio button
echo $answerchoice1;
$answerChoice2 = $_POST('test2');
$answerChoice3 = $_POST('test3');
$answerChoice4 = $_POST('test4');
$answerChoice5 = $_POST('test5');
$answerChoice6 = $_POST('test6');
$answerChoice7 = $_POST('test7');
$answerChoice8 = $_POST('test8');
$answerChoice9 = $_POST('test9');
$answerChoice10 = $_POST('test10');
$correctAnswer = $row['aanswer'];
$score = 0;
if ($answerchoice1 == $correctAnswer){
$score = $score + 1;
} else {
$score = $score;
}
if ($answerchoice2 == $correctAnswer){
$score = $score + 1;
} else {
$score = $score;
}
if ($answerchoice3 == $correctAnswer){
$score = $score + 1;
} else {
$score = $score;
}
if ($answerchoice4 == $correctAnswer){
$score = $score + 1;
} else {
$score = $score;
}
if ($answerchoice5 == $correctAnswer){
$score = $score + 1;
} else {
$score = $score;
}
if ($answerchoice6 == $correctAnswer){
$score = $score + 1;
} else {
$score = $score;
}
if ($answerchoice7 == $correctAnswer){
$score = $score + 1;
} else {
$score = $score;
}
if ($answerchoice8 == $correctAnswer){
$score = $score + 1;
} else {
$score = $score;
}
if ($answerchoice9 == $correctAnswer){
$score = $score + 1;
} else {
$score = $score;
}
if ($answerchoice10 == $correctAnswer){
$score = $score + 1;
} else {
$score = $score;
}
So, when I click on the submit button of the form, I get directed to the mathcheck script with an error. Here is the link to the quiz with the submit button for reference.
http://socialsoftware.purchase.edu/nicholas.roberts/mathquiz/mathselect.php?category=Calculus
change all of your $_POST('x') to $_POST['x']
as it stands now you are trying to access it like a function not an array.
You are loading $correctanswer once. It's not changed for every question ? SO, you need to load each answer before you do the check for that question.
You may have more problems on your code, I couldn't check everything but you may start by putting the input fields inside the form tag, i.e.:
<form action="mathcheck.php" method="post">
<?php
print ("<input type = 'radio' name='test".$strQuestionNumber."' value ='$slots[0]'>".$slots[0]."<br>"); //displaying 4 radio buttons with value of answer choice
print ("<input type = 'radio' name='test".$strQuestionNumber."' value ='$slots[1]'>".$slots[1]."<br>");
print ("<input type = 'radio' name='test".$strQuestionNumber."' value ='$slots[2]'>".$slots[2]."<br>");
print ("<input type = 'radio' name='test".$strQuestionNumber."' value ='$slots[3]'>".$slots[3]."<br>");
print("<br>");
}
}
?>
<input type ="submit" value = "submit">
</form>
Also, the correct syntax of $_POST is:
$_POST['test2'];
NOT
$_POST('test2');
I have an array for flash cards, and using shuffle I am outputting 15 unique cards, 3 each for 5 different categories.
What I want to do is create these card sets for about a dozen people on the same web page, but the part I can't figure out is how to make it so each complete set is unique and doesn't repeat from a set given to any other user.
A short code sample with a brief explanation would be the most helpful to me.
Here is the code I modified to my needs. Not much changed really.
<?php
/* original source:
* 3d10-engine.php
* by Duane Brien
*/
if (empty($_POST)) {
for ($i = 1; $i < 16; $i++) {
$numbers['ALL'][] = $i;
}
$picks = array();
$letters = array ('ALL');
foreach ($letters as $letter) {
for ($i = 0;$i < 10;$i++) {
shuffle($numbers[$letter]);
$chunks = array_chunk($numbers[$letter], 5);
$cards[$i][$letter] = $chunks[0];
if ($letter == 'N') {
$cards[$i][$letter][2] = ' '; // Free Space
}
}
foreach ($numbers[$letter] as $number) {
$balls[] = $letter.$number;
}
shuffle($balls);
}
$cardsstr = serialize($cards);
$ballsstr = serialize($balls);
$picksstr = serialize($picks);
} else {
$cards = unserialize($_POST['cardsstr']);
$balls = unserialize($_POST['ballsstr']);
$picks = unserialize($_POST['picksstr']);
array_unshift($picks, array_shift($balls));
echo "<h1>Just Picked: " . $picks[0] . "</h1>";
$cardsstr = serialize($cards);
$ballsstr = serialize($balls);
$picksstr = serialize($picks);
}
?>
Picks : <?php echo implode(',', $picks) ?>
<form method='post'>
<input type='hidden' name='cardsstr' value='<?php echo $cardsstr ?>' />
<input type='hidden' name='ballsstr' value='<?php echo $ballsstr ?>' />
<input type='hidden' name='picksstr' value='<?php echo $picksstr ?>' />
<input type='submit' name='cards' value='next number' />
</form>
Start Over
<?php
foreach ($cards as $card) {
echo "<table border='1'>";
echo "<tr><td>A</td><td>B</td><td>C</td><td>D</td><td>E</td></tr>";
for ($i = 0; $i < 5; $i++) {
echo "<tr><td>" . $card['B'][$i] . "</td><td>" .$card['I'][$i] . "</td><td>" . $card['N'][$i] . "</td>";
echo "<td>" . $card['G'][$i] . "</td><td>" . $card['O'][$i] . "</td></tr>";
}
echo "</table>";
}
?>
Since you have more options in each set, random pick is enough to achieve unique final result.
I mean don't make this thing more complex.
Try this sample
<?php
//Initialize your 5 sets here
$numbers['B'] = range(1,15);
$numbers['I'] = range(16,30);
$numbers['N'] = range(31,45);
$numbers['G'] = range(45,60);
$numbers['O'] = range(61,75);
//My Assumption is you to pick 3 from each
while(TRUE){
$rand = rand(0,5);
if(count($numbers_B) < 3 && !in_array($numbers['B'][$rand]){
$numbers_B[] = $numbers['B'][$rand];
}
$rand = rand(0,5);
if(count($numbers_I) < 3 && !in_array($numbers['I'][$rand]){
$numbers_I[] = $numbers['I'][$rand];
}
$rand = rand(0,5);
if(count($numbers_N) < 3 && !in_array($numbers['N'][$rand]){
$numbers_N[] = $numbers['N'][$rand];
}
$rand = rand(0,5);
if(count($numbers_G) < 3 && !in_array($numbers['G'][$rand]){
$numbers_G[] = $numbers['G'][$rand];
}
$rand = rand(0,5);
if(count($numbers_O) < 3 && !in_array($numbers['O'][$rand]){
$numbers_O[] = $numbers['O'][$rand];
}
if( count($numbers_B) == 3 && count($numbers_I) == 3 && count($numbers_N) == 3 &&
count($numbers_G) == 3 && count($numbers_O) == 3 ){
break;
}
}
$result = $numbers_B + $numbers_I + $numbers_N + $numbers_G + $numbers_O; ?>
Here $result value should be unique, And I consider number of sets is constant. If it is dynamic, then try the same logic with two dimensional array.
Just store the prepared sets in an array and then check each shuffle if it exists in the array using the already (in_array function) or not, if it does then shuffle again.
On this system a user can create a quiz of any number of questions, that info saves to a database. I'm using the below to output the quiz to the users. This outputs fine and you can only choose one of each answer. Each question has 3 inputs with the same post name, q1 has ans1 ans1 ans1, q2 has ans2ans2 ans2 etc... thats where the ".$x." comes in.
$x = 1;
while($row = mysql_fetch_row($quiz)) {
echo "Question ".$x.": ";
echo "<a><b> $row['question'] </b></a>";
echo "<input type='radio' name='ans".$x." /> ".$row['ans1']."<br />";
echo "<input type='radio' name='ans".$x." /> ".$row['ans2']."<br />";
echo "<input type='radio' name='ans".$x." /> ".$row['ans3']."<br />";
$x = $x + 1;
}
The problem is in the next php page. I'm trying to loop through all posts and where the post matches the correct ans then result = result + 1. I need a loop that does something like this:
$x = 1;
while($row = mysql_fetch_row($quiz)) {
if ($_POST[ans[$x]]=='$row['correct']' { $result = $result + 1;
}
$x = $x + 1;
}
is there a way i can use a variable in that $_POST value to say ans1 ans2 for each loop?
$x = 1;
while($row = mysql_fetch_row($quiz)) {
if ($_POST['ans'.$x] == $row['correct']) { $result = $result + 1; }
$x = $x + 1;
}
Hope this will solve your problem
Try something like this
$x = 1;
while($row = mysql_fetch_row($quiz)) {
echo "Question ".$x.": ";
echo "<a><b> $row['question'] </b></a>";
echo "<input type='radio' name='ans[".$row['ansId']."][".$x."] ' /> ".$row['ans1']."<br />";
echo "<input type='radio' name='ans[".$row['ansId']."][".$x."] ' /> ".$row['ans2']."<br />";
echo "<input type='radio' name='ans[".$row['ansId']."][".$x."] ' /> ".$row['ans3']."<br />";
$x = $x + 1;
}
Your front script:
$x = 1;
while($row = mysql_fetch_row($quiz)) {
if ($_POST['ans'][$row['ansId']][$x]=='$row['correct']' {
$result = $result + 1;
}
$x = $x + 1;
}