array shuffle with key for quiz php - php

<?php
$qq=mysql_query("select * from quiz");
$row=mysql_fetch_array($qq);
//var_dump($row);
$question = $row['question'];
$_SESSION['quiz_id']=$row['id'];
$ans_array = array($row['answer1'],$row['answer2'],$row['answer3'],$row['answer4']);
shuffle($ans_array);
?>
<form name="qform" id="qform">
<h2> <?php echo $question; ?></h2>
<label><input type="radio" value="<?php echo $ans_array[0]; ?>" name="answer"> <?php echo $ans_array[0]; ?></label>
<label><input type="radio" value="<?php echo $ans_array[1]; ?>" name="answer"> <?php echo $ans_array[1]; ?></label>
<label><input type="radio" value="<?php echo $ans_array[2]; ?>" name="answer"> <?php echo $ans_array[2]; ?></label>
<label><input type="radio" value="<?php echo $ans_array[3]; ?>" name="answer"> <?php echo $ans_array[3]; ?></label>
<p id="submit-row-btn"><input type="submit" id="quiz_submit" class="q_submit" value="Submit">
<input type="submit" id="quiz_ans_submit" value="Check Answer" class="q_submit" style="display:none">
<span id="ans_err"></span></p>
</form>
In my MySQL table, I have stored;
id question answer1 answer2 answer3 answer4 ans_key date
1 1+1= 2 3 1 6 1 2014-08-03
here is ans_key;
1 =answer1
2 =answer2
3 =answer3
4 =answer4
I am using Ajax to send user's answer.
I want to check the answer key with the relevant value,
after array shuffle, how to get the key value to check if the answer is right or not?

i found the answer
<?php
$ans_array = array(1=>$row['answer1'],$row['answer2'],$row['answer3'],$row['answer4']);
$shuffleKeys = array_keys($ans_array);
shuffle($shuffleKeys);
$newArray = array();
foreach($shuffleKeys as $key)
{
$newArray[$key] = $ans_array[$key];
?>
<label><input type="radio" value="<?php echo $newArray[$key] ?>" data-key="<?php echo $key;?>" name="answer"> <?php echo $newArray[$key]; ?></label>
<?php
}
?>
here data-key holds the key value of array

Related

How can I get the total count of the selected radio button value

After I click on submit how can I get the count of of how many "Yes" were picked or how many "No" were Picked using PHP
while($row = mysqli_fetch_array($result))
{
$i++;
?>
<p><?php echo $row["question"] ; ?></p>
<input type="radio" name="<?php echo $row["question"].$i ; ?>" value="Yes">
<label for="Yes">Yes</label>
<input type="radio" name="<?php echo $row["question"].$i ; ?>" value="No">
<label for="Bo">No</label>
<?php
}
?>
</div><br>
<input type="submit" name="submit" value="Submit">
</div>
</form>
<?php
if(isset($_POST['submit'])){
//count
}
put in some kind of identifier you can pick up in the $_POST, like
<input type="radio" name="question_radio_<?php echo $row["question"].$i ; ?>" value="Yes">
<label for="Yes">Yes</label>
<input type="radio" name="question_radio_<?php echo $row["question"].$i ; ?>" value="No">
<label for="Bo">No</label>
Then in php
$s = 'question_radio_';
$yes = 0;
foreach ($_POST as $p => $n) {
if (strpos($p, $s) !=== false && $n==='Yes') $yes ++;
}

Selection in Radio Button gets replaced in two divs

I have two questions with radio button (each question having 4 radio) in PHP
But there is single check in all 8 radio buttons, but it should be, with 4-4 radio buttons.
Look: https://imgur.com/Sytl72a
My Code:
<form method="post" enctype="multipart/form-data" class="form-horizontal">
<?php
$lstmt = $user->runQuery("SELECT * FROM mcq WHERE LRN=:lrn ORDER BY Sr ASC ");
$lstmt->bindparam(":lrn",$id);
$lstmt->execute();
if($lstmt->rowCount() > 0)
{
$i=0;
while($lrow=$lstmt->fetch(PDO::FETCH_ASSOC))
{
extract($lrow);
$i++;
?>
<div>
<h1><?php echo $i; ?>) <?php echo $Question; ?></h1></br>
<h2> <input type="radio" name="radio" value="<?php echo $Oa; ?>"> A) <?php echo $Oa; ?></h2>
<h2> <input type="radio" name="radio" value="<?php echo $Ob; ?>"> B) <?php echo $Ob; ?></h2>
<h2> <input type="radio" name="radio" value="<?php echo $Oc; ?>"> C) <?php echo $Oc; ?></h2>
<h2> <input type="radio" name="radio" value="<?php echo $Od; ?>"> D) <?php echo $Od; ?></h2>
</div>
<hr></br></br>
<?php
}
}
?>
<button class="btn btn-large btn-primary" type="submit" name="btn-submit">Submit</button>
</form>
<?php
}
if(isset($_POST['btn-submit']))
{
echo $ufname = trim($_POST['radio']);
}
?>
Update your radio input name attribute just like this,
<div>
<h1><?php echo $i; ?>) <?php echo $Question; ?></h1></br>
<h2> <input type="radio" name="radio<?php echo $i; ?>?>" value="<?php echo $Oa; ?>"> A) <?php echo $Oa; ?></h2>
<h2> <input type="radio" name="radio<?php echo $i; ?>" value="<?php echo $Ob; ?>"> B) <?php echo $Ob; ?></h2>
<h2> <input type="radio" name="radio<?php echo $i; ?>" value="<?php echo $Oc; ?>"> C) <?php echo $Oc; ?></h2>
<h2> <input type="radio" name="radio<?php echo $i; ?>" value="<?php echo $Od; ?>"> D) <?php echo $Od; ?></h2>
</div>
And for submitting:
<?php
}
$count = $i;
for($j = 1; $j <= $count; $j++){ if(isset($_POST['btn-submit'])) {
echo $ufname = trim($_POST['radio'.$j]);
}
}
?>
It will definitely solve your problem,

Store data obtained using foreach loop from view into the database using CodeIgniter

I am trying to store the values obtained from the form into the database. I am stuck where I do not know how to obtain the values individually from foreach($questions as $row) and store them into the database.
My database table has the following columns:
variantid | stepid | questionid | newquestion | radiovalues | description
When I click on save, I am trying to save all the details obtained from the view into the database. every value obtained with each loop of foreach($questions as $row) needs to get stored in a new row. I think I should be using insert_batch, but I do not know how I can put all the data into the array.
How can I proceed with this? The following is the code that I have written. I have not written anything in model as I am stuck.
<form id="theform">
<label for="variants">Variants:</label><br>
<?php
foreach($variants as $row)
{?>
<div class="form-group">
<input type="radio" name="variants[]" checked="true" id="variants" value="<?php echo $row->variantid ?>"/><?php echo $row->variantname ?><br/>
<?php }
?>
<div id='steplist'>
<?php
foreach($substeps as $row){
?>
<div id='img_div'>
<input type="radio" name="stepid[]" checked="true" id="stepid<?php echo $row->stepid; ?>" value="<?php echo $row->stepid; ?>"/><?php echo $row->stepname ?><br/>
</div>
<?php
foreach($questions as $each){
?><br><br>
<input type="text" name="questions[]" id="questions<?php echo $each->questionid; ?>" value="<?php echo $each->questionname; ?>" readonly/><br/>
<input type="hidden" name="questionid[]" id="questions<?php echo $each->questionid; ?>" value="<?php echo $each->questionid; ?>"/>
<a id="addq">Add question</a>
<input type="text" class="form-control" name="newquestion[]" style="font-weight:bold;width:100%;height:5%" id="new_questions<?php echo $each->questionid; ?>" /><br>
<div class="radio" id="answer">
<label style="font-weight:bold"><input type="radio" name="radioquestions[<?php echo $each->questionid; ?>][optradio]" value="no" required>no</label>
<label style="font-weight:bold"><input type="radio" name="radioquestions[<?php echo $each->questionid; ?>][optradio]" value="probably no" required>probably no </label>
<label style="font-weight:bold"><input type="radio" name="radioquestions[<?php echo $each->questionid; ?>][optradio]" value="unknown" required>unknown</label>
<label style="font-weight:bold"><input type="radio" name="radioquestions[<?php echo $each->questionid; ?>][optradio]" value="probably yes" required>probably yes</label>
<label style="font-weight:bold"><input type="radio" name="radioquestions[<?php echo $each->questionid; ?>][optradio]" value="yes">yes</label>
</div>
<textarea name="question1_text[]" id="description<?php echo $each->questionid; ?>" rows="3" cols="73"></textarea><br>
<?php
}
?>
<?php
}
?>
</div>
</form>
<input type='button' value='Save' class='save' id='save' />
<script>
$(document).ready(function(){
$("#save").click(function(e){
e.preventDefault();
$.ajax({
type:"POST",
url:"<?= base_url() ?>index.php/task/perform",
data:$('#theform').serialize(),
success:function(response){
alert(response);
}
});
});
});
This is my controller:
public function perform(){
var_dump($_POST);
$variantid = $this->input->post('variants');
$stepid = $this->input->post('stepid');
$questionid = $this->input->post('questions');
$newquestion = $this->input->post('newquestion');
$radioquestions = $this->input->post('radioquestions');
$question1_text = $this->input->post('question1_text');
$this->load->model('task_model');
$result= $this->task_model->performdata();
if($result){
echo "Data saved successfully";
}
}
Update
Thank you for the quick reply. I changed the code according to the suggestion. How can I get these values into the controller and send them into the database?
The HTML inside the foreach is invalid as it is missing a closing div tag and your input does not have the correct name attribute, for multiple inputs you should use variants[] and not the same ID. Do it in this manner:
<?php foreach ($variants as $row) { ?>
<div class="form-group">
<input type="radio" name="variants[]" checked="true" class="variants" value="<?php echo $row->variantid ?>"/><?php echo $row->variantname ?><br/>
</div>
<?php } ?>

PHP form with radio buttons - make only one answer required, second optional

I have this PHP form with radio buttons:
{
$agreements = jm_get_application_setting( 'application_agreements', '' );
if( empty( $agreements ) ) return;
$questions = explode( "\n", $agreements );
if (!empty($questions)):
foreach ($questions as $index => $question) :
?>
<div class="form-group">
<p><strong for="question-<?php echo sanitize_title($question); ?>" ><?php echo $question; ?></strong></p>
<div class="form-control-flat">
<label class="radio">
<input type="radio" name="_noo_application_answer_<?php echo $index; ?>" value="1" required><i></i><?php echo esc_html__('Do il consenso', 'noo'); ?>
</label>
</div>
<div class="form-control-flat">
<label class="radio">
<input type="radio" name="_noo_application_answer_<?php echo $index; ?>" value="0" required><i></i><?php echo esc_html__('Nego il consenso', 'noo'); ?>
</label>
</div>
<input type="hidden" name="_noo_questions[]" value="<?php echo esc_attr($question); ?>"/>
</div>
<?php
endforeach;
endif;
}
How can I make only one answer required to validate the form?
I mean.. Just the first MUST be selected, but I also need to show the second one for "legal reasons".
As is, this form accepts both choices as acceptable.
You can set a variable for the condition, and change it's value at the end of first iteration.
if (!empty($questions)):
$first = 1; // <----- HERE
foreach ($questions as $index => $question) :
?>
<div class="form-group">
<p><strong for="question-<?php echo sanitize_title($question); ?>" ><?php echo $question; ?></strong></p>
<div class="form-control-flat">
<label class="radio">
<input type="radio"
name="_noo_application_answer_<?php echo $index; ?>"
value="1"
<?php echo $first ? "required" : ""; ?>> // <----- HERE
<i></i><?php echo esc_html__('Do il consenso', 'noo'); ?>
</label>
</div>
<div class="form-control-flat">
<label class="radio">
<input type="radio"
name="_noo_application_answer_<?php echo $index; ?>"
value="0"
<?php echo $first ? "required" : ""; ?>> // <----- HERE
<i></i><?php echo esc_html__('Nego il consenso', 'noo'); ?>
</label>
</div>
<input type="hidden" name="_noo_questions[]" value="<?php echo esc_attr($question); ?>"/>
</div>
<?php
$first = 0; // <----- HERE
endforeach;
endif;

Getting values of radio buttons generated in for loop

I'm currently running on codeigniter framework and running into some trouble. I am retrieving a list of questions and a list of their possible answers (something like a questionnaire) from the database and loading it out to participants to attempt.
Due to the the for loop I'm using, I'm unable to change the name or id value of individual questions. I sort of overcome this by appending the questionID to the name/id.
The trouble comes here when i post this over to my controller. How am I able to differentiate it when I need to insert it the results back into the database?
<?php foreach($dbresult->result() as $row) {?>
<p><?php echo $row->Question ;?></p>
<?php if ($row->QuestionType == "MCQ"){ ?>
<ul>
<li><b>A: </b><?php echo $row->SelectionA; ?></li>
<li><b>B: </b><?php echo $row->SelectionB; ?></li>
<li><b>C: </b><?php echo $row->SelectionC; ?></li>
<li><b>D: </b><?php echo $row->SelectionD; ?></li>
</ul>
Select one of the following options:<br>
<input type="radio" name="<?php echo $row->QuestionID;?>.Ans" required value="A">A<br>
<input type="radio" name="<?php echo $row->QuestionID;?>.Ans" value="B">B<br>
<input type="radio" name="<?php echo $row->QuestionID;?>.Ans" value="C">C<br>
<input type="radio" name="<?php echo $row->QuestionID;?>.Ans" value="D">D<br>
<?php } elseif($row->QuestionType== "truefalse") {?>
Select one of the following options:<br>
<input type="radio" name="<?php echo $row->QuestionID;?>.Ans" value="true">True<br>
<input type="radio" name="<?php echo $row->QuestionID;?>.Ans" value="false">False<br>
<?php } else {?>
<input type="radio" name="<?php echo $row->QuestionID;?>.Ans" value="ok">OK<br>
<input type="radio" name="<?php echo $row->QuestionID;?>.Ans" value="agree">Agree<br>
<?php }?>
<?php } ?>
The above is the way I have printed the questionnaire out, any possible solutions for this?
Thats hard to manage having a name attribute like that.
Use a grouping name attribute:
name="answers[<?php echo $row->QuestionID;?>]"
Simple example:
<?php foreach($dbresult->result() as $row) {?>
<p><?php echo $row->Question ;?></p>
<?php if ($row->QuestionType == "MCQ"){ ?>
<ul>
<li><b>A: </b><?php echo $row->SelectionA; ?></li>
<li><b>B: </b><?php echo $row->SelectionB; ?></li>
<li><b>C: </b><?php echo $row->SelectionC; ?></li>
<li><b>D: </b><?php echo $row->SelectionD; ?></li>
</ul>
Select one of the following options:<br>
<input type="radio" name="answers[<?php echo $row->QuestionID;?>]" required value="A">A<br>
<input type="radio" name="answers[<?php echo $row->QuestionID;?>]" value="B">B<br>
<input type="radio" name="answers[<?php echo $row->QuestionID;?>]" value="C">C<br>
<input type="radio" name="answers[<?php echo $row->QuestionID;?>]" value="D">D<br>
<?php } elseif($row->QuestionType== "truefalse") {?>
Select one of the following options:<br>
<input type="radio" name="answers[<?php echo $row->QuestionID;?>]" value="true">True<br>
<input type="radio" name="answers[<?php echo $row->QuestionID;?>]" value="false">False<br>
<?php } else {?>
<input type="radio" name="answers[<?php echo $row->QuestionID;?>]" value="ok">OK<br>
<input type="radio" name="answers[<?php echo $row->QuestionID;?>]" value="agree">Agree<br>
<?php }?>
<?php } ?>
So that in PHP, you could just call it by its name:
public function controller_name()
{
$answers = $this->input->post('answers');
foreach($answers as $question_id => $answer) {
}
}

Categories