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');
Related
I am trying to embed a self-referencing PHP script inside an HTML form with following code:
Undefined index: conv
<form action = "<?php $_SERVER['PHP_SELF'] ?>" method = "post">
<input type = "number" id = "temp2" name = "temperature2" placeholder = "28">
<label for = "temp2"> degrees </label>
<select>
<option name = "conv" value = "f"> Fahrenheit </option>
<option name = "conv" value = "c"> Celsius </option>
</select>
<input type = "submit" value = "equals">
<?php
$type = $_POST["conv"];
$tmp = $_POST["temperature2"];
if ($type == "f") {
$newTmp = (9/5 * $tmp) + 32;
echo $newTmp . " degrees Celsius.";
}
elseif ($type == "c") {
$newTmp = (5 * ($tmp - 32)) / 9;
echo $newTmp . " degrees Fahrenheit.";
}
?>
</form>
And I am getting this messages:
Notice: Undefined index: conv
Notice: Undefined index: temperature2
Everything worked fine when the PHP script was in another file.
Anyone knows what am I doing wrong?
You must verify that you was send the page and $_POST exist. And correct the select element
<form action = "<?php $_SERVER['PHP_SELF'] ?>" method = "post">
<input type = "number" id = "temp2" name = "temperature2" placeholder = "28">
<label for = "temp2"> degrees </label>
<select name = "conv">
<option value = "f"> Fahrenheit </option>
<option value = "c"> Celsius </option>
</select>
<input type = "submit" value = "equals">
<?php
if(isset($_POST["temperature2"])) {
$type = $_POST["conv"];
$tmp = $_POST["temperature2"];
if ($type == "f") {
$newTmp = (9/5 * $tmp) + 32;
echo $newTmp . " degrees Celsius.";
}
elseif ($type == "c") {
$newTmp = (5 * ($tmp - 32)) / 9;
echo $newTmp . " degrees Fahrenheit.";
}
}
?>
</form>
The variable ($type = $_POST["conv"];) is not set until the form is processed. Do
if (!empty($_POST["conv"])) {
$type = $_POST["conv"];
}
Here is my answer...
First, it is better to verify, is it submitted or not ??, if submit button is invoked then code proceed rest. Else you get error. Moreover result and variable will not be shown until you click the submit button.
<form action = "<?php $_SERVER['PHP_SELF'] ?>" method = "post">
<input type = "number" id = "temp2" name = "temperature2" placeholder = "28">
<label for = "temp2"> degrees </label>
<select name = "conv">
<option value = "f"> Fahrenheit </option>
<option value = "c"> Celsius </option>
</select>
<input type = "submit" name="submit" value = "equals">
<?php
if(isset($_POST["submit"])) {
$type = $_POST["conv"];
$tmp = $_POST["temperature2"];
if ($type == "f") {
$newTmp = (9/5 * $tmp) + 32;
echo $newTmp . " degrees Celsius.";
}
elseif ($type == "c") {
$newTmp = (5 * ($tmp - 32)) / 9;
echo $newTmp . " degrees Fahrenheit.";
}
}
?>
</form>
Your PHP code will run every time you load the page, not only when someone presses submit. This means it looks out there for $_POST['conv'] and $_POST['temperature2'] but doesn't find anything because the form hasn't been posted.
You need to name your submit button and then surround all your PHP processing with an if like this:
<input type = "submit" name="mysubmit" value = "equals">
<?php
if (#$_POST['mysubmit']) {
$type = $_POST["conv"];
$tmp = $_POST["temperature2"];
if ($type == "f") {
$newTmp = (9/5 * $tmp) + 32;
echo $newTmp . " degrees Celsius.";
}
elseif ($type == "c") {
$newTmp = (5 * ($tmp - 32)) / 9;
echo $newTmp . " degrees Fahrenheit.";
}
}
?>
Now it will only look at that PHP code when someone has actually submitted something. Putting the # before the #$_POST['mysubmit'] makes it so you don't get the same error that you were getting before on this new array key.
I'm trying to display different images from the database that are in the same field but the result is echoed either as "m" or "Array".
Here's my code:
$badges = $row['badges'];
$badges = explode(",", $badges);
$badge = count($badges);
if(empty($badges)) {
$badges = "";
} else {
$i = 0;
while($i <= $badge) {
$badges = "<img src='".$badges[$i]."' /> ";
$i++;
}
}
$rank = "<tr><td><img src='".$rank."' /> ".$badges."</td></tr>";
$rank is then echoed to the div that I want it to be displayed but the image src is always "m" or when I try putting the while in place of the $rank variable it echoes as "Array". Does anyone know why this is?
I would use another variable name, like badgeString as the output. Also, it seems like you want to append all the badges
if(empty($badges)) {
$badgeString = "";
} else {
$i = 0;
while($i <= $badge) {
$badgeString .= "<img src='".$badges[$i]."' /> ";
$i++;
}
}
$rank = "<tr><td><img src='".$rank."' /> ".$badgeString."</td></tr>";
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;
}
i need a help
in php i have a select box like this
<?php
$perpage = 5;
$total = 128;
$num = ceil( $total / $perpage );
$i = 1;
echo "<FORM NAME=\"form1\">";
echo "Select <SELECT NAME=\"select\" onChange=\"goto(this.form)\" SIZE=\"1\" >";
echo "<OPTION VALUE=\"\">----Select Page----";
for($i = 1; $i <= $num; $i++)
{
$sel = $i;
$goto = ($i - 1) * $perpage;
if($goto == 0) { $goto = ''; }
echo "<OPTION VALUE=\"http://localhost/CI_doctrine/blog/filmnews/" . $goto . "\">" . $i . "";
}
echo "</SELECT> Page";
echo "</FORM>";
?>
javascript code is here
function goto(form) {
var index = form.select.selectedIndex;
if (form.select.options[index].value != "0") {
window.location = form.select.options[index].value;
form.select.selected = form.select.options[index].value;
}
}
the code is working fine but i want to change the selected option to set the selected number after the page redirection but here iam getting the "select page" as the selected option
any help appreciated.
thank you from your friend.
Once you redirect, that page is unloaded and a new page loaded (even if it has the same items). When the new page loads, you want to do:
window.onload = function() {
var i, options = form.select.options, curUrl = window.location.href;
for (i = 0; i < options.length; i++) {
if (options[i].value == curUrl) {
form.select.selectedIndex= i;
break;
}
}
}
This will select the current URL. Make sure the URLs in the select options are full URLs (including http://). Also, window.onload is the DOM1 way. You should probably use a real library to deal with this.
Alternatively, you can also select the right input in PHP using the same basic approach.