Populate array with values from different <option> drop down - php

I find this concept kinda confusing.
So basically i have a while loop in PHP that is used to retract display a question and its possible answers from a database. I also have populated a drop down list ( using select tag) with those possible answers. What im trying to achieve is, through a form, to send an array with values from all the currently selected options of the tag. This is the part of the code if that makes it easier to understand.
echo "<select name='quiz_question' id='quiz_question' required>";
while ($row = $result2->fetch_assoc()) {
$answer = $row['answer'];
$answer_id = $row['id'];
echo "<option value='$answer_id'>$answer</option>";
}
echo "</select>";
Any ideas on how i could achieve populating an array with elements that have the same value name since they are in a loop it would be great.

Found the answer that i was looking for. Posting it here in case someone else stumbles across my question.
Bare in mind that i'm populating my array with "id" which is an integer.
echo "<select name='Quiz_answers[]' id='quiz_question' >";
while ($row = $result2->fetch_assoc()) {
$answer = $row['answer'];
$answer_id = $row['id'];
echo "<option value='$answer_id'>$answer</option>";
}
echo "</select>";

Related

How to check if radio button contains correct answers?

I have 2 tables in my database, 1 for questionnaires and 1 for correct answers. both have id linked to each other. code for displaying questions
while($row = $result->fetch_assoc()) {
echo "<br><label>". $row["Question"] ."</label><br><br>";
echo "<input type='radio' name='ans' value='ans1'>". $row["AnswerA"] ."</label><br>";
echo "<input type='radio' name='ans' value='ans2'>". $row["AnswerB"] ."</label><br>";
echo "<input type='radio' name='ans' value='ans3'>". $row["AnswerC"] ."</label><br>";
}
and then when user hits submit, the it should check if the radio button which contains the correct answer. code for checking answers
while($row = $result->fetch_assoc()) {
if(isset($_POST['submit'])){
if($_POST['ans']== $row["CorrectAns"]) {echo "Correct";}
else {echo "Incorrect";}
}
}
I think this will work for only one question. However I have about 20 questions and 3 radio buttons each. What addition should i add while checking the answer? I am trying to avoid javascript in this one but if there is a simple js solution I am open for it
First, reduce the database round trips and reduce rows fetched from database.
If you have multiple questions, get all the correct answers from database for these questions. Then create one array with correct answers $answers[question_id] = $answer;.
Then check for all the answers submitted by the user with actual answers.
<?php
if(isset($_POST['submit'])){
// $_POST['ans'] is array for all questions
$submittedAnswers = [];
$correctAnswers = [];
foreach ($_POST['ans'] as $questionID => $answer) {
$submittedAnswers[$questionID] = $answer;
}
// use mysql binding for actual query in production
//$sql = "select * from answers where Question_ID in {" . implode(',', array_keys($submittedAnswers)) . "}";
while($row = $result->fetch_assoc()) {
$correctAnswers[$row["Question_ID"]] = $row["CorrectAns"];
}
$failedQuestions = [];
foreach ($submittedAnswers as $questionID => $answer) {
if ($answer != $correctAnswers[$questionID]) {
$failedQuestions[] = $questionID;
}
}
}

PHP changing from Single answer Option field to Hidden field

I have a working code where the result of a query is passed to another page. The query comes with only a single answer which is what I want. What I want however is for the field I am passing to be hidden. There is also an option field with multiple answers being passed at the same time, which has to remain. So what I'm asking is for a proper way to pas the hidden field so I don't get all the errors when I do it the way I was trying (ie The wrong way)
Here's the working code that I have. I want the first option field to be a hidden field. Any help is appreciated
$studentquery="SELECT * from student ORDER BY ssurname";<br>
//Do Query
$studentresult = mysql_query ($studentquery);
$options="";
echo "<form action='addstudenttofamily1c.php' method='POST'>";
$familychoice = "SELECT * from hostfamily WHERE hid= '".mysql_real_escape_string($hostfamily). "'";
$resultfamilychoice = mysql_query ($familychoice);
$options2="";
echo "<select name='element_1' id='element_1'>";
while ($rowfam=mysql_fetch_array($resultfamilychoice))
{
echo "<option value='$rowfam[hid]'>$rowfam[hfsurname] $rowfam[hfmname]</option><br/>";
}
echo "</select>";
echo "<select name='element_3' id='element_3'>";
while($row=mysql_fetch_array($studentresult))
{
echo "<option value='$row[sid]'>$row[sname] $row[ssurname]</option>";
}
echo "</select><input type='submit' name='submit3' value='Replace Student'>";
echo "</form>";
echo"</td>";
echo" </tr>";
This is how you can store a hidden value for a form:
<input type="hidden" name="SomeHiddenField" val="ValueOfThisField" />
To which you could code it in PHP to make it dynamic also.

How to prevent echoing same value twice in php

So I have this drop down list in my form which pull "tags" from database as value for drop down options:
<select name="cartags">
<?php $result = mysql_query("SELECT * FROM Products WHERE ID > '0'");
while($row = mysql_fetch_array($result))
{
echo "<option value=\""; echo $row['Tag']; echo "\""; echo ">"; echo $row['Tag']; echo "</option>";
}
?>
</select>
What is my problem? My problem is that I am adding a lot of products into my databas and my code make dropdown list with tags for all this producst even if they have same tag. So what I need is solution how to prevent that same tag appear twice in my drop down.
I am pretty new to PHP and this is my first question here so I really hope that I explained my problem well.
Thanks in advance!
What is the purpose of WHERE ID > '0'? If ID is an auto-increment then it will always be positive. If not, it should be.
Why are you using mysql_fetch_array and then only using the associative keys? You should use mysql_fetch_assoc instead.
Why are you using a new echo every time you want to output a variable? Just concatenate.
Why are you setting the same string in value as the option's text? Without a value, it defaults to the text anyway.
Why are you not using backticks around your column and table names?
Try this instead:
<select name="cartags">
<?php
$result = mysql_query("SELECT DISTINCT `Tag` FROM `Products`");
while(list($tag) = mysql_fetch_row($result)) {
echo "<option>".$tag."</option>";
}
?>
</select>
Try this
<select name="cartags">
<?php $result = mysql_query("SELECT Tag, COUNT(Tag) tg Products WHERE ID > '0' GROUP BY Tag HAVING COUNT(Tag)>0 ORDER BY tg DESC");
while($row = mysql_fetch_array($result))
{
echo "<option value=\""; echo $row['tg']; echo "\""; echo ">"; echo $row['tg']; echo " </option>";
}
?>
</select>
It will also display the top tags that have the most first.

PHP dynamic dropdown menu list - default value

I'm trying to create a default value for my dynamic drop down list. After the user selects one of the options, they submit and that value is stored as a variable in the next page that I can access using $_POST['land']
I have created the same dynamic list in the next page and want that 'land' to appear first in the dynamic drop down menu. So far this is just the main code to show the dynamic drop down list. Any help would be appreciated. Thanks!
while($row = mysqli_fetch_assoc($result))
{
extract ($row);
echo "<option value='$place'>$place</option>\n";
}
As far as I understand you want the item chosen on first page to appear as the default item in the second page.
Use this
while($row = mysqli_fetch_assoc($result))
{
extract ($row);
echo "<option value='$place'";
echo ((isset($_POST['land']) && $_POST['land']==$place)?'selected="selected"':'');
echo ">$place</option>\n";
}
while($row = mysqli_fetch_assoc($result))
{
extract ($row);
echo "<option value='$place' ";
if($_POST['land'] == $place) {
echo "selected='selected'";
}
echo ">$place</option>\n";
}
while($row = mysqli_fetch_assoc($result))
{
extract ($row);
$select = (isset($_POST['land']) && $_POST['land'] == $place)?"selected='selected'":"";
echo "<option value='$place' $select >$place</option>\n";
}

Using PHP to populate a <select></select> dropdown? [duplicate]

This question already has answers here:
Fetching data from MySQL database to HTML dropdown list
(4 answers)
Closed 7 months ago.
<select name="select">
</select>
I want to populate the above tag with values from database.
I have written PHP code up to this.
while($row=mysql_fetch_array($result))
{
}
$row is fetching correct values. How to add it to the <select>
What about something like this :
echo '<select name="select">';
while($row=mysql_fetch_array($result))
{
echo '<option value="' . htmlspecialchars($row['column_for_value']) . '">'
. htmlspecialchars($row['column_for_label'])
. '</option>';
}
echo '</select>';
Of course, up to you to decide which items from $row should be used for the value and the text of each <option>
Just make sure you are escaping the data that comes from your DB -- especially if it can contain HTML ; as you are outputting HTML, this can be done with htmlspecialchars or htmlentities.
Note that those might take a couple of additionnal parameters that I didn't use in my example -- setting those can be useful, depending on the charset you're using.
You can see whats available to use by doing this in the while:
var_dump($result);
exit;
That will print the first result and its array contents. Then you can see what field you want to use to populate the option. From there, you would do something like:
foreach ($result['field'] as $field) {
print '<option value="'.$field.'">$field</option>';
}
Of course this is a very basic example, and as others have noted you may want to clean the data before putting it into a form.
$selected_value="selected_value";
echo '<select name="select">';
while($row=mysql_fetch_array($result))
{
if($selected_value==htmlspecialchars($row['column_for_value']))
$selected=' selected';
else
$selected='';
echo '<option value="'.htmlspecialchars($row['column_for_value']).'"'.$selected.'>'
.htmlspecialchars($row['column_for_label']).
'</option>';
}
echo '</select>';
Some addition to Pascal MARTIN code, for auto selection of some predefined value
I editied the last entry to this and it works perfectly. The only hassle I have now is once the user has submitted the form the dropdown goes blank... Does anyone know a simple solution
echo '<select name="course" id="course" >';
while( $option = mysql_fetch_array($course_results)) {
echo "<option value=".htmlspecialchars($option['cid']).">".htmlspecialchars($option['cname'])."</option>";
}
echo "</select>";
All the above answers will work, but are not proper and require extra work. You should not use echo to output to the screen and you don't have to. The below example assumes you are using objects containing data, but you get the idea.
<select name="sales_person">
<?php foreach ($sales_people as $sales_person){?>
<option value="<?=$sales_person->first_name?> <?=$sales_person->last_name?>"><?=$sales_person->first_name?> <?=$sales_person->last_name?></option>
<?php }?>
</select>
The point being you don't have to echo out the html
echo "<select>";
while( $option = mysql_fetch_array($result)) {
echo "<option>".htmlspecialchars($option['column'])."</option>";
}
echo "</select>";
echo '<select>';
while($row=mysql_fetch_array($result)) {
echo '<option>'.$row['whatever_index'].'</option>';
}
echo '</select>';
Replace 'whatever_index' with the column name you are fetching.

Categories