I have a quiz test page where I want to test the user for knowledge.
I did it so it works, but it has a flaw.
This is my code for populating the quiz with questions and (possible) answers from a mysql database:
echo '<form action="'.$_SERVER["PHP_SELF"].'" method="post" id="quiz">';
$sql=mysql_query("SELECT idtest,no_q,title_q,q,idteste_dtl,corect_a from teste_dtl where idtest=".$idtest." order by no_q");
$num = mysql_num_rows($sql);
$i=0;
while ($row=mysql_fetch_row($sql)) {
echo '<h3 style="color:#e74c3c">'.$row[2].'</h3>';
echo '<p data-toggle="tooltip"><strong>'.$row[3].'</strong></p>';
$ssql=mysql_query("select letter,answer from tests_answers where idtest=".$idtest." and idq=".$row[4]." order by letter");
while ($rrow=mysql_fetch_row($ssql)) {
$Label = 'question-'.$row[1].'-answers-'.$rrow[0];
echo '<div>';
echo '<label class="radio">';
echo '<input type="radio" data-toggle="radio" name="answers['.$row[1].']" id="'.$Label.'" value="'.$rrow[0].'" unchecked>';
echo $rrow[0].') '.$rrow[1];
echo '</label>';
echo '</div>';
}
echo ' <br>';
echo '<input type="hidden" name="question['.$row[1].']" value="'.$row[2].'">';
echo '<input type="hidden" name="corect_a['.$row[1].']" value="'.$row[5].'">';
echo '<input type="hidden" name="idemp" value="'.$idemp.'">';
echo '<input type="hidden" name="idtest" value="'.$idtest.'">';
echo '<input type="hidden" name="idfirm" value="'.$idfirm.'">';
echo '<input type="hidden" name="namefirm" value="'.$namefirm.'">';
echo '<input type="hidden" name="totalq" value="'.$num.'">';
}
echo' <input type="submit" class="btn btn-hg btn-primary" value="Check answers" />';
echo '</form>';
So basically I generate a pair of text (question) + radioboxes (possible answers) from 2 tables. Table 1 is called "teste_dtl" and Table 2 is called "tests_answers".
All works perfectly except there is a bug. If the user does not check a radio box in a question... my code seems to think that the first radio box was checked.
So I have something like:
Question ONE
Body of question one... some text... and so on
A) first answer
B) second answer
C) third answer
D) fourth answer
Question TWO
Body of question two... some text... and so on
A) first answer
B) second answer
C) third answer
D) fourth answer
...
So the A,B,C,D... are checkboxes (input type radio). They are all unchecked from the start.
When I POST the results... apparently the questions that were not answered (no radio was checked) are considered as "answered with answer A)"
How can I avoid this?
Thank you
Radio buttons are supposed to always have a value.
The HTML specification says: "If no radio button in a set sharing the same control name is initially 'on', user agent behavior for choosing which control is initially 'on' is undefined." This means, practically, that depending on the browser and/or the Javascript library used to submit the form (if you're using AJAX), you can get unpredictable results.
You should force one of the buttons to be selected either by inserting checked="checked" like this:
$first_answer = true; // Set a flag for the first answer
while ($rrow=mysql_fetch_row($ssql)) {
$Label = 'question-'.$row[1].'-answers-'.$rrow[0];
echo '<div>';
echo '<label class="radio">';
// Output the beginning of the INPUT tag
echo '<input type="radio" data-toggle="radio" name="answers['.$row[1].']" id="'.$Label.'" value="'.$rrow[0].'"';
if ( $first_answer ) { // When the flag is true...
echo ' checked="checked"'; // ...add the 'checked' parameter...
$first_answer = false; // ...and set the flag to false for the next round
}
echo '/>'; // Close the INPUT tag
echo $rrow[0].') '.$rrow[1];
echo '</label>';
echo '</div>';
}
Another option is to add some Javascript to check that the user has selected an answer.
Related
Hello I think I am really close but I just cant seem to get my statement working correctly
I have a overtime field from Mysql and I can display it but I am trying to make it either checked or not checked depending on if it is a 1 for checked or 0 for not checked. I can show the 1 or the 0 onto a Text field but the checkbox just won't work for me.
echo '<td> Overtime <input type="checkbox" name="chg_hrs_ovt[]" <? if($list_hours["overtime"]==1){ echo "checked=checked"} ?> >';
My complete code:
<?
// This next section is to load the text fields from the mysql
// this is to collect all of the logged hours on the job sheet and then display
// the hours already entered.
$hours_query = "SELECT * FROM hours where job_number = '$job_number'";
$hours_result= ($mysqli-> query($hours_query));
// this next section collects the data from the parts table and then adds it to an array
// this then goes into a while statement until it has displayed all of the results it has
// depending on how many parts were used
while ($list_hours = mysqli_fetch_array($hours_result))
{
echo " <table border ='0' table width = 70%>";
echo '<td> <input type="hidden" name="chg_hrs_id[]" value="'.$list_hours['unique_id'].'">';
echo '<td> Start Time <input type="time" name="chg_hrs_str[]" value="'.$list_hours['start_time'].'" >';
echo '<td> Finish Time <input type="time" name="chg_hrs_fin[]" value="'.$list_hours['finish_time'].'">';
echo '<td> Date Of Work <input type="date" name="chg_hrs_date[]" value="'.$list_hours['date'].'">';
echo '<td> Ovt Boolean <input type="ovt_Booloean" name="chg_hrs_ovtb[]" value="'.$list_hours['overtime'].'">';
echo '<td> Overtime <input type="checkbox" name="chg_hrs_ovt[]" <? if($list_hours["overtime"]==1){ echo "checked=checked"} ?> >';
echo "</tr>";
}
echo "</table>";
?>
I think you have some Syntax issues. Try the following:
echo '<td> Overtime <input type="checkbox" name="chg_hrs_ovt[]"' . ($list_hours["overtime"]==1 ? 'checked="checked"' : '') . '>';
Thanks to Marc I had got the syntax incorrect I have used Marc's syntax and it has worked straight away. I now have to see how the statement is put together.
It seems like the dots is a link to connect statements together and it doesn't seem to actually need a if statement to be setup.
please i am currently working on a school result computation project in php. I have a page that gets all the students that enrolled for a particular subject. A while loop generates three textboxes against each student's name(CA1, CA2, and Exam). Please can anyone help me with a solution?? When the form is submitted only the last entry enters the database. Below is my code.
<?php
session_start();
include 'header_staff.php';
$subject=$_POST['subject'];
$user_id=$_SESSION['user_id'];
$get=mysql_query("SELECT * FROM staffrecord WHERE user_id='$user_id'",$conn);
$go=mysql_fetch_array($get);
$class=$go['class_id'];
$sql=mysql_query("SELECT * FROM student_enrollment WHERE class_id='$class' AND subject_id='$subject'",$conn);
echo '<form action="submitrslt.php" method="post">';
while($subj=mysql_fetch_array($sql)){
echo $subj['name'];
echo '<input type="text" name="ca1" />';
echo '<input type="text" name="ca2" />';
echo '<input type="text" name="exam" /><br><br>';
}
echo '<input type="submit" value="submit" />';
?>
The solution to your problem is to use your input arrays by simply adding [] to the input names:
while($subj=mysql_fetch_array($sql)){
echo $subj['name'];
echo '<input type="text" name="ca1[]" />';
echo '<input type="text" name="ca2[]" />';
echo '<input type="text" name="exam[]" /><br><br>';
}
Further, you can use the primary key of your table as the index in each iteration (let's suppose this would be $subj['id'], but if it is more meaningful in your case, you can also use $subj['name'] as the index):
while($subj=mysql_fetch_array($sql)){
echo $subj['name'];
echo '<input type="text" name="ca1[<?php echo $subj['id'] ?>]" />';
echo '<input type="text" name="ca2[<?php echo $subj['id'] ?>]" />';
echo '<input type="text" name="exam[<?php echo $subj['id'] ?>]" /><br><br>';
}
This way you can easily identify values from the resulting array after the post.
PS: Be sure you never trust user input without verifying or sanitizing it - make sure $_POST['subject'] is numeric. You can find plenty of useful tips on how to achieve this.
I have added comments, this will solve your problem i am assuming your subjects data is unique for the loop. And i have defined the input with the subject name which make it unique. Just for an example you can try your own method. This will output all the post variables on your action(form post) screen.
<?php
while($subj=mysql_fetch_array($sql)){
$subname = str_replace(' ','', $subj['name']); //just to replace the space
echo $subj['name'];
echo '<input type="text" name="'.$subname.'_ca1" />'; //to make the field unique for the input entries
echo '<input type="text" name="'.$subname.'_ca2" />';
echo '<input type="text" name="'.$subname.'_exam" /><br><br>';
}
echo '<input type="submit" value="submit" />';
echo '</form>';
?>
Firstly, I would suggest changing the connection to mysqli, which follows a very similar syntax to mysql except that it is not deprecated.
Secondly, the form looks fine, except that the textboxes and submit button don't have any unique identifiers, you might try putting in a unique 'id' for each of the input fields. Since your loop is combining all input fields in one form, this is likely the culprit. Furthermore, I don't see a closing tag for form, i.e. </form>.
Finally, you should look up filter_input for handling superglobals such as $_POST[].
I assume that all fields are meant to be submitted at once rather than individually?
I wasn't sure how to word the title, because just thinking about this concept kind of confuses me and I'm not sure why. I'm sure there is some simple solution to this.
Here is a picture of my codes (Attached below) output.
The user should be able to click 1 radiobox inside each box, but I can't seem to make it do that. The way it is right now, only 1 vacation button can be selected and only 1 absent button can be selected.
Here is my code:
if($loop < 4) {
echo '<td>';
echo ' NAME<BR><input type="radio" name="vacationTeammates[]" value="'.$value[0].'">Vacation<br>
<input type="radio" name="absentTeammates[]" value="'.$value[0].'">Absent';
echo '</td>';
$loop++;
} else {
$loop = 1;
echo "</tr><tr align='center'>";
echo '<td>';
echo ' NAME<BR><input type="radio" name="vacationTeammates[]" value="'.$value[0].'">Vacation<br>
<input type="radio" name="absentTeammates[]" value="'.$value[0].'">Absent';
echo '</td>';
}
(The loop makes it so that the table row ends and starts a new one, so it is somewhat irrelevant but the radio buttons are what matters)
Each radio button pair must have the same "name" attribute value for browsers to know they're their own set.
Change your code to something like this, where "$SomeUniqueRowVar" is a variable that changes for each row:
echo 'NAME<BR>';
echo '<input type="radio" name="status'.$SomeUniqueRowVar.'" value="vacation">';
echo 'Vacation<br>';
echo '<input type="radio" name="status'.$SomeUniqueRowVar.'" value="absent">';
echo 'Absent';
I would add a counter and assign each name to a specific array element, rather than just []. Since you only want one of the radios to be selectable for each teammate, the inputs will have to be the same name but have different values. Put the teammates name in an array (a variable separate from the radio inputs) that uses the counter as it's index. This way you know which response goes to which teammate.
if($loop < 4) {
$name[$counter] = $value[0];
echo '<td>';
echo ' NAME<BR><input type="radio" name="teammates[$counter]" value=1>Vacation<br>
<input type="radio" name="teammates[$counter]" value=0>Absent';
echo '</td>';
$counter++;
$loop++;
} else {
$name[$counter] = $value[0];
$loop = 1;
echo "</tr><tr align='center'>";
echo '<td>';
echo ' NAME<BR><input type="radio" name="teammates[$counter]" value=1>Vacation<br>
<input type="radio" name="teammates[$counter]" value=0>Absent';
echo '</td>';
$counter++;
}
Now when you process the array, you will know if teammates[$counter] is 1 it means vacation and 0 it means absent.
You could also opt to use the name AS the index if you can be sure it is free of special characters/safely parse special chars out.
Thank you #user3163495 & #FirstOne for a few tips I used in my answer here.
I made both of the radio buttons in each cell have the same name, and all the others have different names.
if($loop < 4) {
echo '<td>';
echo ' <input type="radio" name="goneTeammates['.$uniqueLoop.']" value="'.$value[0].'|V">Vacation<br>
<input type="radio" name="goneTeammates['.$uniqueLoop.']" value="'.$value[0].'|A">Absent<br>NAME';
echo '</td>';
$loop++;
} else {
$loop = 1;
echo "</tr><tr align='center'>";
echo '<td>';
echo ' <input type="radio" name="goneTeammates['.$uniqueLoop.']" value="'.$value[0].'|V">Vacation<br>
<input type="radio" name="goneTeammates['.$uniqueLoop.']" value="'.$value[0].'|A">Absent<br>NAME';
echo '</td>';
}
For the value, I used the teammates name (Actually their uniqueid) and an A for absent or V for vacation. The output would basically look like:
35|A
23|V
64|A
etc
On the processing side I explode()'d the input at that | sign, to basically get the uniqueID and the letter in seperate variables, and processed like normal from there.
I'm trying to make a form with checkboxes which should subscribe a user to a forum in the database eventually.
I use this code to dynamically create a list of subscribed/unsubscribed forums for the current user:
//$checkboxes = array();
echo' <form action="" method="post">';
while($unsubscrlist = mysql_fetch_assoc($sublist))
{
//$checkboxes[] = $unsubscrlist['Name'];
echo '<input type="checkbox" checked="checked" name="subscrform[]"
value="' .$unsubscrlist['Name']. ' "/>' .$unsubscrlist['Name']. ' <br />';
}
while($subscrlist = mysql_fetch_assoc($notsublist))
{
// $checkboxes[] = $subscrlist['Name'];
echo '<input type="checkbox" name"subscrform[]"
value="' .$subscrlist['Name']. '"/>' .$subscrlist['Name']. '<br />';
}
echo '<br />
<input type="submit" value="Submit" />
</form>';
Then, to determine which checkboxes are checked I use this code:
if($_SERVER['REQUEST_METHOD'] == 'POST')
{
if(isset($_POST['subscrform']))
{
//echo 'getshereeee';
foreach($_POST['subscrform'] as $value)
{
//echo 'getshereeee';
echo $value;
}
}
Now the first checkboxes - to which the user is already subscribed -are output as value by this code, while the second list of checked checkboxes is never output as value somehow..
I thought this might had to do with using the same name twice. So I changed the first list to unsubscrform and did the check loop loop for both but still only get the first list as output values.
I feel like I'm missing something simple but can't really find out what. I would very much appreciate your help!
I just found a solution to my problem!
by changing
echo' <form action="" method="post">';
to
echo' <form name="subscrform" action="" method="post">';
When my user searches for game in my DB, I present them with a list of the games that match their search term, and then i want to add a button to each item that allows the user to select "have it" or "want it" then have a single "add" button that adds their selections to their profile.
because you cant have it and want it at the same time, i assumed a radio button would be the best choice.
but now i am lost as to how to handle the buttons. When i click on one selection from the search, it will deselect when i choose have or want on another game.
I understand that i should be creating a separately name form for each search result, but then how would i manage the data when sending it to my controller? Maybe i need incrementing form names and then count how many results and use that in my controller?
Also, i need the gameID associated with the selections so i need to send a hidden value with that data for each selection
maybe i am going about this the wrong way...
heres my code
echo '<div id="UserSearchGameResults">';
echo '<form action="#" method="Post">';
$x = 0;
while($gamesLike != null)
{
$x++;
echo '<div id="game_search_list_item">'.$x.'. '.$gamesLike['title'].'</div>
<span class="gamelistblue">
<input type="radio" name="haveOrWant" value="have" />Have it
</span>
<span class="gamelistorange">
<input type="radio" name="haveOrWant" value="want" />Want it
</span>
<input type="hidden" name="gameID" value="'.$gamesLike['ID'].'" />';
$gamesLike = $statement->fetch();
}
$statement->closeCursor();
echo '<br /> <input type="submit" value="Add Game(s)" />';
echo '</div></form>';
any help is appreciated with the subject
new ideas on how to handle my needs are welcome too.
Dan
Use arrays for the input names. Something like
<input type="radio" name="game' . $gamesLike['ID'] . '[haveOrWant]" value="have" />Have it