Combine array and MySQL results - php

I have a quiz that uses an array to store the questions:
$array=array(
'1'=> array('1','What does everyone know when they see it?','quest1','Good publicity','Bad punctuation', 'Good business writing', 'Bad spelling','../images/example03.jpg'),
'2'=> array('2','What do people write instead of \'now\'?','quest2','Presently','At this moment in time', 'Currently', 'At the present time','../images/example03.jpg'),
);
I then display the questions using this loop:
foreach($array as $quiz)
{
echo
'<div class="question">
<div class="questionList">
<h4>' . $quiz[0] . '. <strong>' . $quiz[1] . '</strong></h4>
<ul>
<li><input type="radio" name="' . $quiz[2] . '" value="1"> '. $quiz[3] . '</li>
<li><input type="radio" name="' . $quiz[2] . '" value="2"> '. $quiz[4] . '</li>
<li><input type="radio" name="' . $quiz[2] . '" value="3"> '. $quiz[5] . '</li>
<li><input type="radio" name="' . $quiz[2] . '" value="4"> '. $quiz[6] . '</li>
</ul>
</div>
<img src="'. $quiz[7] . '" class="questionImg01" />
<div class="clr"></div>
</div>
';
}
}
If someone doesn't answer all the questions the first time, I store the values for each question in MySQL or "0" if there was no answer. I would like to check the radio buttons that the user has already answered, but can't work out how to combine the quiz array and the MySQL results.
The table structure for the results is:
quiz_id | username | quest1 | quest2 | quest3 | quest4 | quest5 | quest6 | quest7 | quest8 | quest9 | quest10 | complete
Where quiz_id is the reference number for that quiz and complete is a flag to record if the user has answered all the questions. I'm retrieving the results like this:
$results = mysql_query("SELECT * FROM quiz_results_baseline WHERE username = ('$username')");
Is there a way I can combine these two?
I also have the problem where I can't make this query include a WHERE statement - I would like to store all the quiz results in one table and then refer to each user's quiz results using the quiz_id:
mysql_query("INSERT INTO quiz_results_baseline (quest1,quest2,quest3,quest4,quest5,quest6,quest7,quest8,quest9,quest10,username,quiz_id,complete) VALUES $queryData ON DUPLICATE KEY UPDATE quest1=VALUES(quest1),quest2=VALUES(quest2),quest3=VALUES(quest3),quest4=VALUES(quest4),quest5=VALUES(quest5),quest6=VALUES(quest6),quest7=VALUES(quest7),quest8=VALUES(quest8),quest9=VALUES(quest9),quest10=VALUES(quest10),complete=VALUES(complete)");
Any help would be appreciated!

In order to get your half completed quiz results to render along with the quiz, try the following code.
$questions=array(
'1'=> array('1','What does everyone know when they see it?','quest1','Good publicity','Bad punctuation', 'Good business writing', 'Bad spelling','../images/example03.jpg'),
'2'=> array('2','What do people write instead of \'now\'?','quest2','Presently','At this moment in time', 'Currently', 'At the present time','../images/example03.jpg'),
);
// do your query for the row of answers
// $answers = mysql_fetch_assoc(...);
// for testing
$answers = array(
'quest1' => '1',
'quest2' => '4');
for($i = 1; $i <= count($questions); $i++)
{
$quiz = $questions[$i];
$answer = $answers[$quiz[2]];
echo
'<div class="question">
<div class="questionList">
<h4>' . $quiz[0] . '. <strong>' . $quiz[1] . '</strong></h4>
<ul>
<li><input type="radio" name="' . $quiz[2] . '" value="1" ' . (($answer == '1') ? 'checked' : '') . '> '. $quiz[3] . '</li>
<li><input type="radio" name="' . $quiz[2] . '" value="2" ' . (($answer == '2') ? 'checked' : '') . '> '. $quiz[4] . '</li>
<li><input type="radio" name="' . $quiz[2] . '" value="3" ' . (($answer == '3') ? 'checked' : '') . '> '. $quiz[5] . '</li>
<li><input type="radio" name="' . $quiz[2] . '" value="4" ' . (($answer == '4') ? 'checked' : '') . '> '. $quiz[6] . '</li>
</ul>
</div>
<img src="'. $quiz[7] . '" class="questionImg01" />
<div class="clr"></div>
</div>
';
}
You will have to do your query to get the $answers array, but I put in an example so you can see how to use the result.
I ran the code and the results looks like this:
Hope that helps!

Related

Add class to label with class if radio is checked

I want to add a class 'checked' to the <span class="label product-option"> when a radio button is checked and remove when a other radio is checked.
How can I extend my code for this?
$htmlValue = $_value->getOptionTypeId();
if ($arraySign) {
$checked = (is_array($configValue) && in_array($htmlValue, $configValue)) ? 'checked' : '';
} else {
$checked = $configValue == $htmlValue ? 'checked' : '';
}
$spanClass = "input-radio";
if ($checked) {
$spanClass = "input-radio checked";
}
$selectHtml .= '<li>' . '<span class="input-radio"><input type="' . $type . '" class="' . $class . ' ' . $require
. ' product-custom-option"'
. ($this->getSkipJsReloadPrice() ? '' : ' onclick="opConfig.reloadPrice()"')
. ($this->helper('core')->currencyByStore($_value->getPrice(true), $store, false) ? '0' : ' checked="checked"')
. ' name="options[' . $_option->getId() . ']' . $arraySign . '" id="options_' . $_option->getId()
. '_' . $count . '" value="' . $htmlValue . '" ' . $checked . ' price="'
. $this->helper('core')->currencyByStore($_value->getPrice(true), $store, false) . '" /></span>'
. '<span class="label product-option' . $spanClass . '"><label for="options_' . $_option->getId() . '_' . $count . '"><span class="option-name">'
. $this->escapeHtml($_value->getTitle()) . '</span>' . $priceStr . '</label></span>';
if ($_option->getIsRequire()) {
$selectHtml .= '<script type="text/javascript">' . '$(\'options_' . $_option->getId() . '_'
. $count . '\').advaiceContainer = \'options-' . $_option->getId() . '-container\';'
. '$(\'options_' . $_option->getId() . '_' . $count
. '\').callbackFunction = \'validateOptionsCallback\';' . '</script>';
}
$selectHtml .= '</li>';
Your code shows that you already know how to tell if an element is checked or not, and how to set variables containing class names.
Just extend that logic.
$spanClass = "input-radio";
if ($checked) {
$spanClass = "input-radio checked";
}
...
'<span class="' . $spanClass . '">'
I didn't bother to check you php-code to find out how the html would look like exactly (maybe use Streams next time?), but you need to register an eventhandler like this:
(using jQuery as you seem to already be using it anyways)
$('.input-radio input[type=radio]').change(function() {
// $('.input-radio.checked').removeClass('checked'); // this works if you only have one .input-radio
/* if you want multiple (with different names) */
// note: template string are only available in ES6, if you use earlier versions, use the + to concatinate strings
$(`.input-radio.checked input[type=radio][name=${this.name}]`)
.parents('.input-radio.checked').removeClass('checked');
$(this).parents('.input-radio').addClass('checked');
});
/* This CSS is NOT needed and is only used for effect */
.wrapper span {
display: block;
/* To make them vertically aligned, usually makes no sense for span I know */
}
span.input-radio.checked {
background-color: yellow;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="wrapper">
<span class="input-radio checked">
<label>
Radio Button
<input type="radio" name="myRadio" checked/>
</label>
</span>
<span class="input-radio">
<label>
Radio Button
<input type="radio" name="myRadio"/>
</label>
</span>
<span class="input-radio">
<label>
Radio Button
<input type="radio" name="myRadio"/>
</label>
</span>
<span class="input-radio">
<label>
Radio Button
<input type="radio" name="myRadio"/>
</label>
</span>
<span class="input-radio">
<label>
Radio Button
<input type="radio" name="myRadio"/>
</label>
</span>
<span class="input-radio">
<label>
Radio Button
<input type="radio" name="myRadio"/>
</label>
</span>
</div>
As a side note, personally I prefer using data-attributes for things like this instead of classes as that more clearly separates design from function.

Querying for checking quiz in php [duplicate]

This question already has answers here:
The 3 different equals
(5 answers)
Closed 5 years ago.
querying is my problem to choose the correct answer .
.
.
.
please answer my problem
*
<?php
$sql = "SELECT * FROM questions_exam_tbl WHERE exam_id = '" . $_POST['subject'] . "'";
$result = mysql_query($sql) or die(mysql_error());
while($row = mysql_fetch_array($result)){
if($row['test_num'] = $qnumber){
echo '
<h3>' . $row['test_num']. '. ' . $row['test_question'] . '</h1>
<input type="radio" name="choiceA" value="' . $row['choice_A'] . '"> ' . $row['choice_A'] . '
<input type="radio" name="choiceA" value="' . $row['choice_B'] . '"> ' . $row['choice_B'] . '
<input type="radio" name="choiceA" value="' . $row['choice_C'] . '"> ' . $row['choice_C'] . '
<input type="radio" name="choiceA" value="' . $row['choice_D'] . '"> ' . $row['choice_D'] . '
';
}
}
?>
*
if($row['test_num'] = $qnumber)
should be
if($row['test_num'] == $qnumber)
Single = is for value assigning. For comparison it is == or ===.

Check the answer and verify from database whether it is correct or not in PHP

Fetching questions from database and displaying in screen now what should be the logical part or how to implement for checking if selected answer is correct or not and how to store correct answer in database and verifying them.
Here is the code
<?php
// Create connection
$conn = new mysqli("localhost","root","","QuizQuestions");
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully<br><br>";
$sql = "SELECT Question, Answer1, Answer2, Answer3, Answer4 FROM Questions";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
$i = 1;
while ($row = $result->fetch_assoc()) {
echo "<br>Question: " . $row["Question"] . "<br>";
echo ' A) <input type="radio" name="ans' . $i . '" value="' .
$row["Answer1"] . '">' . $row["Answer1"] . '<br>';
echo ' B) <input type="radio" name="ans' . $i . '" value="' .
$row["Answer2"] . '">' . $row["Answer2"] . '<br>';
echo ' C) <input type="radio" name="ans' . $i . '" value="' .
$row["Answer3"] . '">' . $row["Answer3"] . '<br>';
echo ' D) <input type="radio" name="ans' . $i . '" value="' .
$row["Answer4"] . '">' . $row["Answer4"] . '<br>';
$i++;
}
} else {
echo "0 results";
}
$conn->close();
?>
Because all of the radio inputs have the same name. They all will be considered as same radio group. You need to have different names for different questions. Something like -
$i = 1;
while ($row = $result->fetch_assoc()) {
echo "<br>Question: " . $row["Question"] . "<br>";
echo ' A) <input type="radio" name="ans' . $i . '" value="' . $row["Answer1"] . '">' . $row["Answer1"] . '<br>';
echo ' B) <input type="radio" name="ans' . $i . '" value="' . $row["Answer2"] . '">' . $row["Answer2"] . '<br>';
echo ' C) <input type="radio" name="ans' . $i . '" value="' . $row["Answer3"] . '">' . $row["Answer3"] . '<br>';
echo ' D) <input type="radio" name="ans' . $i . '" value="' . $row["Answer4"] . '">' . $row["Answer4"] . '<br>';
$i++;
}
You also can use the row id instead of the of $i.
You have set same name for all radio buttons. You should group the radio buttons for each question. For that you can get the question id from the database and set the radio button name like
echo ' A) <input type="radio" name="ans'.$row["id"].'"
value="'.$row["Answer1"].'">'.$row["Answer1"].'<br>';
Make sure you have different names for each input field in the radio group so that it treats each question as a different record.

Populating checkbox from server side data using 2 loops

I have a need to check the checkboxes which values are available in the database, with that i has to display additional options avaialable also.
I was trying, as i am using two loops it's repeating the same set of checkboxes and check differnt values in each instance.
I need to check the appropriate checkboxes in first loop itself. Is there any way to achieve this
The following was my output
Output of the code
Following is the code i am using
$sid;//Retrived from DB
$iDLst=array();
$sql1 = "SELECT
`id1`
FROM `tbl1`
where `tbl1_sid`='" . $sid . "'";
$result1 = $conn->query($sql1);
if ($result1->num_rows > 0) {
while ($row = $result1->fetch_assoc()) {
$iDLst[]=$row['id1'];
}
}
foreach ($iDLst as $id){
$sql2 = "SELECT
`id`,
`nme`
FROM `tbl2`;
";
$result2 = $conn->query($sql2);
if ($result2->num_rows > 0) {
while ($rowC = $result2->fetch_assoc()) {
if (strpos($rowC['id'], $id) !== FALSE ) {
echo ' <input value="' . $rowC['id'] . '" type="checkbox" name="upD[]" checked/> <label>' . $rowC['nme'] . ' </label>';
} else {
echo ' <input value="' . $rowC['id'] . '" type="checkbox" name="upD[]" /> <label>' . $rowC['nme'] . ' </label>';
}
}
}
}
Note: I have changed to general code, There is no errors in code. I am getting the display. I need the solution regarding the logic part...
I think you can replace this:
if (strpos($rowC['id'], $id) !== FALSE ) {
echo ' <input value="' . $rowC['id'] . '" type="checkbox" name="upD[]" checked/> <label>' . $rowC['nme'] . ' </label>';
} else {
echo ' <input value="' . $rowC['id'] . '" type="checkbox" name="upD[]" /> <label>' . $rowC['nme'] . ' </label>';
}
with this:
echo ' <input value="' . $rowC['id'] . '" type="checkbox" name="upD[]" ' . strpos($rowC['id'], $id) ? 'checked ' : '' . '/> <label>' . $rowC['nme'] . ' </label>';
It's a ternary statement that says if strpos($rowC['id'], $id) evaluates true, 'checked ' will be in the enclosing echo statement, otherwise '' will be in the enclosing echo statement.
I have found the way after some research.
The way i am doing is only half part.
Following code will do the work addition to the provided code.
//Print the checkbox with checeked for the values in array
foreach ($iDLst as $id){
$sql2 = "SELECT
`id`,
`nme`
FROM `tbl2`;
";
$result2 = $conn->query($sql2);
if ($result2->num_rows > 0) {
while ($rowC = $result2->fetch_assoc()) {
echo ' <input value="' . $rowC['id'] . '" type="checkbox" name="upD[]" checked/> <label>' . $rowC['nme'] . ' </label>';
}
}
}
//Print the checkbox without checeked for the values Not in array
$sql3 = "$sql2 = "SELECT
`id`,
`nme`
FROM `tbl2` where id NOT IN (" . implode(',', array_map('intval', $iDLst)) . "); ";
$result3 = $conn->query($sql3);
if ($result3->num_rows > 0) {
while ($rowC = $result3->fetch_assoc()) {
echo ' <input value="' . $rowC['id'] . '" type="checkbox" name="upD[]"/> <label>' . $rowC['nme'] . ' </label>';
}
}
the following questions lead me the way to do this
MySQL PHP - SELECT WHERE id = array()? [duplicate]
mysql syntax on not equal many values

How can I adjust the position of a label for a zend form Radio element?

with this piece of code
$feOnline = New Zend_Form_Element_Radio('online');
$feOnline->setValue($article->online)
->addMultiOptions(array(0=>'offline', 1=>'online'))
->setLabel('Online');
this html is generated
<dd id="online-element">
<label for="online-0">
<input type="radio" checked="checked" value="0" id="online-0" name="online">offline
</label><br>
<label for="online-1"><input type="radio" value="1" id="online-1" name="online">online
</label>
</dd>
However I don't want the input-tag inside the label-tag. No need for the "" either...
What decorators must I add to get this output?
<dd id="online-element">
<input type="radio" checked="checked" value="0" id="online-0" name="online"><label for="online-0">offline</label>
<input type="radio" value="1" id="online-1" name="online"><label for="online-1">online</label>
</dd>
If you are using default Zend_View_Helper_FormRadio you can't change the way radio is rendered.
The code is as follows (line 159)
// Wrap the radios in labels
$radio = '<label'
. $this->_htmlAttribs($label_attribs) . ' for="' . $optId . '">'
. (('prepend' == $labelPlacement) ? $opt_label : '')
. '<input type="' . $this->_inputType . '"'
. ' name="' . $name . '"'
. ' id="' . $optId . '"'
. ' value="' . $this->view->escape($opt_value) . '"'
. $checked
. $disabled
. $this->_htmlAttribs($attribs)
. $endTag
. (('append' == $labelPlacement) ? $opt_label : '')
. '</label>';
No configuration is in place to change the logic.
Think of the reason why you REALLY need to change the way it is rendered, try using CSS to style the output for example.
If you conclude, you need to change rendering, create your own view helper and use it instead of the default one.

Categories