I am using the following code for display questions and answers from admin.
<?php
$select_faq = "Select `intFaqid`, `varQuestion`,`varAnswer` FROM `tbl_faq`";
$selectfaq_result = mysql_query($select_faq);
$select_faqnum = mysql_num_rows($selectfaq_result);
if($selectfaq_result > 0)
{
while($fetch_faq = mysql_fetch_array($selectfaq_result))
{
$faqid = $fetch_faq['intFaqid'];
$fquestion = strip_tags(ucfirst(stripslashes(nl2br($fetch_faq['varQuestion']))));
$fanswer = strip_tags(ucfirst(stripslashes(nl2br($fetch_faq['varAnswer']))));
?>
<h3><?php echo $fquestion; ?></h3>
<p><?php echo $fanswer; ?></p>
<?php
}
}
?>
I need to display the question number before the question. I used the following code for display the question number.
<?php
$questionno = 1;
$numberlimit = $select_faqnum;
while($questionno<=$numberlimit)
{
echo $questionno;
$questionno++;
}
?>
But i doesn't know how to display the question number before the question by combining both the codes. I need the output should display the question with question number. How can i do that?
Am I missing something? I am not sure why you would make it so complex.
Since your recordset is already determining the number of rows, why not just do this:
if($selectfaq_result > 0)
{
//initialise your variable
$question_number = 0;
while($fetch_faq = mysql_fetch_array($selectfaq_result))
{
//increment your variable
$question_number++;
$faqid = $fetch_faq['intFaqid'];
$fquestion = strip_tags(ucfirst(stripslashes(nl2br($fetch_faq['varQuestion']))));
$fanswer = strip_tags(ucfirst(stripslashes(nl2br($fetch_faq['varAnswer']))));
?>
//concatenate the string to include the variable.
//Don't forget to leave a space after it so it looks pretty
<h3><?php echo $question_number . ": " . $fquestion; ?></h3>
<p><?php echo $fanswer; ?></p>
<?php
}
Your line number will finish when you run out of records
<?php
$select_faq = "Select `intFaqid`, `varQuestion`,`varAnswer` FROM `tbl_faq`";
$selectfaq_result = mysql_query($select_faq);
$select_faqnum = mysql_num_rows($selectfaq_result);
if($select_faqnum > 0)
{
$question_number = 0;
while($fetch_faq = mysql_fetch_array($selectfaq_result))
{
$question_number++;
$faqid = $fetch_faq['intFaqid'];
$fquestion = strip_tags(ucfirst(stripslashes(nl2br($fetch_faq['varQuestion']))));
$fanswer = strip_tags(ucfirst(stripslashes(nl2br($fetch_faq['varAnswer']))));
?>
<h3><?php echo "$question_number. $fquestion"; ?></h3>
<p><?php echo $fanswer; ?></p>
<?php
}
}
?>
is that what you are looking for ?
Related
i am creating a quiz website using php where there are 4 questions for users to answer. there is a home page before this for them to choose either math or lit that they wish to do.
after selecting the subject, user need to answer the question and submit their answer, then the php code will calculate their score and count the number of correct/wrong answers.
<ArrayquesAns.php> is the array of questions and answers
it looks something like this, there are 2 array in this php, 1 is math question and another 1 is lit question
and here is the main code where it will generate questions from the question pool randomly. i also tried to put in the code to calculate score
<html>
<body>
<?php
require_once 'ArrayQuesAns.php'; //retrieve array of ques
$_SESSION["subject"] = $_GET['subject']; //suppose to put value when session starts
$_SESSION["name"] = $_GET['name'];
$subject = $_SESSION["subject"];
$name = $_SESSION["name"];
$url = "displayScore.php?name=" . $name . "&subject=" . $subject . "&";
if ($subject == "mathematics") { //math session
$mathQues_key = array_rand($Mathques, 4); //Pick 4 random rows in array
$MathquesRand = array(); //New array to contain the 4 random rows
$i = 0;
foreach ($mathQues_key as $key) {
$MathquesRand[$i] = $Mathques[$key];
$i++;
}
?>
<form action="<?= $url ?>" method="get">
<h1> Section : <?= $subject ?> </h1>
<p>Hello <?= $name ?>! You may start your quiz !<p>
<hr>
<?php foreach ($MathquesRand as $qtsno => $value) { ?>
<?php echo $value["ques"] . " = \t"; ?> <!--Display Question -->
<input type="text" name="userans" value="<?php echo isset($_GET["userans"]) ? $_GET["userans"] : ''; ?>">
<br>
<?php } ?>
<?php
foreach ($MathquesRand as $qtsno => $value) {
array_key_exists($userans = $_GET["userans"]);
$score = 0;
$overall = 0;
$correct = 0;
$wrong = 0;
if ($userans == $value["ans"]) {
$correct += 1;
} else {
$wrong += 1;
}
$score = ($correct * 5) - ($wrong * 3);
"\n\n\n";
echo $value["ans"];
echo $correct;
echo $wrong;
echo $score;
}
?>
<br>
<button type="submit">SUBMIT ATTEMPT</button>
</form>
<?php
} else { //Lit Section
$LitQues_key = array_rand($Litques, 4);
$LitquesRand = array();
$i = 0;
foreach ($LitQues_key as $key) {
$LitquesRand[$i] = $Litques[$key];
$i++;
}
?>
<form action="<?= $url ?>" method="get">
<h1> Section : <?= $subject ?></h1>
<p>Hello <?= $name ?> ! You may start your quiz !<p>
<hr>
<?php foreach ($LitquesRand as $qtsno => $value) {
echo $value["ques"], " = \t";
?> <!--Display Question -->
<input type="text" name="userans" value="<?php echo isset($_GET["userans"]) ? $_GET["userans"] : ''; ?>">
<br>
<?php } ?>
<?php
foreach ($MathquesRand as $qtsno => $value) {
array_key_exists($userans = $_GET["userans"]);
$score = 0;
$overall = 0;
$correct = 0;
$wrong = 0;
if ($userans == $value["ans"]) {
$correct += 1;
} else {
$wrong += 1;
}
$score = ($correct * 5) - ($wrong * 3);
"\n\n\n";
echo $value["ans"];
echo $correct;
echo $wrong;
echo $score;
}
?>
<br>
<button type="submit">SUBMIT ATTEMPT</button>
</form>
<?php
}
?>
<!--Exit-->
<button type="button">EXIT</button>
</body>
</html>
i think this part is where it has issue
foreach ($MathquesRand as $qtsno => $value) {
array_key_exists($userans = $_GET["userans"]);
$score = 0;
$overall = 0;
$correct = 0;
$wrong = 0;
if ($userans == $value["ans"]) {
$correct += 1;
} else {
$wrong += 1;
}
$score = ($correct * 5) - ($wrong * 3);
"\n\n\n";
echo $value["ans"];
echo $correct;
echo $wrong;
echo $score;
}
the code should match user input answer with array question/answer to see if the answer is correct. every correct question will *5 and every wrong answer will *3 (the formula is in the code).
i am not sure if i place the code in the wrong bracket hence its not working or there is some logic error or should i run the code to find the score in a separate php?
after user submit their answer, it will redirect to another page that display their score and number of correct/wrong answers like this
score display html
Based on your original version of the MC test, please find below a working version:
To make it simple, I have removed the "Name" and "Subject" of the form to demonstrate the necessary coding.
You can still use the array_rand to draw 4 random questions
However, after the questions are displayed to the student (and student can input the answer) and clicked "Submit Attempt", the page will remember the random questions drawn - I have used a trick :- to store the questions randomly drawn into a hidden input box
The system will compare the student's submitted answer with that of the correct answer and determine whether it is correct or wrong, and show the score
To fix the "undefined array" errors you encountered, I applied the isset function on places relating to the $_GET variables. (Actually these are warnings, not errors, but it is for sure a good practice to use isset)
<?php
//require_once 'ArrayQuesAns.php'; //retrieve array of ques
$Mathques=array(
1=> array('no'=>1, 'ques'=>"3+1", 'ans'=>"4"),
2=> array('no'=>2, 'ques'=>"3+3", 'ans'=>"6"),
3=> array('no'=>3, 'ques'=>"3+4", 'ans'=>"7"),
4=> array('no'=>4, 'ques'=>"3+5", 'ans'=>"8"),
5=> array('no'=>5, 'ques'=>"3+6", 'ans'=>"9"),
6=> array('no'=>6, 'ques'=>"3+7", 'ans'=>"10"),
7=> array('no'=>7, 'ques'=>"3+8", 'ans'=>"11"),
8=> array('no'=>8, 'ques'=>"3+9", 'ans'=>"12"),
9=> array('no'=>9, 'ques'=>"3+10", 'ans'=>"13"),
10=> array('no'=>10, 'ques'=>"3+11", 'ans'=>"14")
);
if (! isset($_GET["draw"])) {
$mathQues_key = array_rand($Mathques, 4); //Pick 4 random rows in array
}
$MathquesRand = array(); //New array to contain the 4 random rows
if (! isset($_GET["draw"]) ) {
$i = 0;
foreach ($mathQues_key as $key) {
$MathquesRand[$i] = $Mathques[$key];
$i++;
}
}
?>
<?php
if (isset($_GET["draw"]) && $_GET["draw"] !="") {
$pieces = explode(",", $_GET["draw"]);
$index=0;
while ($index < count($pieces)) {
if ($pieces[$index]!=""){
$MathquesRand[] = $Mathques[$pieces[$index]];
}
$index++;
}
}
?>
<form action="" method="get">
<?php
$correct=0;
$wrong=0;
?>
<h1> Section : Mathematics </h1>
<p>Hello ! You may start your quiz !<p>
<hr>
<?php
$pool="";
$ii=1;
foreach ($MathquesRand as $qtsno => $value) {
$pool.= $value["no"]. ",";
?>
<?php echo $value["ques"] . " = \t"; ?> <!--Display Question -->
<input type="text" name="userans<?php echo $ii; ?>"
<?php if (isset($_GET["userans".$ii]))
{
echo " value='" .$_GET["userans".$ii] . "'>" ;
} else { echo ">" ; }
?>
<?php if (isset($_GET["userans".$ii]) && $_GET["userans".$ii]==$value["ans"]) {
$correct++;
} else {
$wrong++;
}
?>
<br>
<?php
$ii++;
}
?>
<input name=draw type=hidden value="<?php echo $pool; ?>">
<br>
<button type="submit">SUBMIT ATTEMPT</button>
</form>
<?php
$score = ($correct * 5) - ($wrong * 3);
?>
<?php if (isset($_GET["draw"])) { ?>
<font color=red>Result:</font>
<br>Correct:<?php echo $correct;?>
<br>Wrong:<?php echo $wrong;?>
<br>Score:<?php echo $score;?>
<?php } ?>
To share my experience (I have coded such Multiple Choice Q & A functions many times) , in future if you want to do similar thing, please consider using
database to store the drawn questions ;
use ajax to compare the input data with the correct data stored in the db, instead of using form submission
I am having a problem in adding the product as a variable with variations. I am trying to add accessories on every product page but its working for simple product and is creating the problem in a variable or with variations
i tried to solve this
//this variable code is not working//
<?php if($currentProduct->get_type() == "variable"){ ?>
var varRules = $(".variations_form").data('product_variations');
<?php foreach($currentProduct->get_attributes() as $k=>$v){ ?>
var attribute_<?= getVar($k) ?> = $("select[name=attribute_<?= $k ?>]").val();
<?php } ?>
$.each(varRules,function(){
<?php
$cond = [];
foreach($currentProduct->get_attributes() as $k=>$v){
$cond[] = '(this.attributes["attribute_'.$k. '"]=='. 'attribute_'.getVar($k).' || this.attributes["attribute_'.$k. '"]=="")';
} ?>
if(<?=implode(" && ", $cond)?>){
total = this.display_price;
}
});
//not even this grouped one//
<?php } else if($currentProduct->get_type() == "grouped"){ ?>
var total = 0;
<?php foreach($currentProduct->get_children() as $k=>$id){ ?>
total += $("[name='quantity[<?= $id ?>]']").val() * <?= getPrice(wc_get_product($id)); ?>;
<?php } ?>
<?php } else { ?>
total = parseFloat(<?= getPrice($currentProduct) ?>);
<?php } ?>
i want it to work for variable products
As it seems that you are using php inside some jQuery code, there are some errors like:
Your php opening tags should all be always like <?php but not like <?=
When you want to display something like a variable from php in jQuery, dont forget echo
Dont forget missing ; before your closing php tags.
I have revisited your code, but nobody can test it as it's an extract with missing things and the context is also missing from your question.
<?php if($currentProduct->get_type() == "variable"){ ?>
var varRules = $(".variations_form").data('product_variations');
<?php foreach($currentProduct->get_attributes() as $k => $v){ ?>
var attribute_<?php echo getVar($k); ?> = $("select[name=attribute_<?php echo $k; ?>]").val();
<?php } ?>
$.each(varRules,function(){
<?php
$cond = [];
foreach($currentProduct->get_attributes() as $k=>$v){
$cond[] = '(this.attributes["attribute_'.$k.'"]=='. 'attribute_'.getVar($k).' || this.attributes["attribute_'.$k.'"]=="")';
} ?>
if(<?php echo implode(" && ", $cond) ?>){
total = this.display_price;
}
});
//not even this grouped one//
<?php } else if($currentProduct->get_type() == "grouped"){ ?>
var total = 0;
<?php foreach($currentProduct->get_children() as $k=>$id){ ?>
total += $("[name='quantity[<?php echo $id; ?>]']").val() * <?php echo getPrice(wc_get_product($id)); ?>;
<?php } ?>
<?php } else { ?>
total = parseFloat(<?php echo getPrice($currentProduct); ?>);
<?php } ?>
I am currently working on a search system and I want to display all rows that have 2 column names, problem is, my while loop only displays 1 row when I have 2 of them in the DB. I've been working my head around this for hours but I just can't get it. The only output I get is the last price.
<?php
include_once("inc/head.php");
include_once("inc/db.php");
$leave = $_POST['departure'];
$come = $_POST['destination'];
$leavedate = $_POST['leavedate'];
$comedate = $_POST['comedate'];
$sql = "select * from flights where departure = '$leave' and destination ='$come'";
$result = $db->query($sql);
$row = $result->fetchObject();
$price = $row->price;
$mostflights = $row->departure;
$mostcomings = $row->destination;
?>
<div>
<ul class="flights">
<?php
while($row = $result->fetchObject())
$price = $row->price;
$mostflights = $row->departure;
$mostcomings = $row->destination;
{ ?>
<li>
<h3><?php echo $mostflights; ?></h3>
<h2><?php echo $mostcomings; ?></h2>
<h2><?php echo $price; ?></h2>
</li>
<?php
}
?>
</ul>
</div>
remove this block at 10th line
$row = $result->fetchObject();
$price = $row->price;
$mostflights = $row->departure;
$mostcomings = $row->destination;
I have been trying to display a menu name from my CMS database that I created myself, I got it displayed perfectly but there is a really weird error, I spent many hours to discover the solution but I couldn't.
The problem is that I want to display the menu name as page H1 in line 50 exactly so whenever you click on the menu name its also displaying as H1 title.
The menu name is displaying correctly, but the sub menu(pages) displaying N instead of the page name, I don't know where is that N is coming from.
NOTE: There is no problem with the database connection or retrieving data.
This is my content page code:
<?php include("includes/header.php"); ?>
<?php require_once 'includes/db_connection.php'; ?>
<?php require_once 'includes/b_functions.php'; ?>
<?php require_once 'includes/cms_constants.php'; ?>
<?php db_connect();?>
<?php
if (isset ( $_GET ['subj'] )) {
$sel_subject = get_subject_by_id ( $_GET ['subj'] );
$sel_page = "NULL";
} elseif (isset ( $_GET ['pages'] )) {
$sel_subject = false;
$sel_page = get_page_by_id ( $_GET ['pages'] );
} else {
$sel_subject = "NULL";
$sel_page = "NULL";
}
?>
<table id="structure">
<tr>
<td id="navigation">
<ul class="subjects">
<?php
$subject_set = get_all_subjects();
while ($subject = mysql_fetch_array($subject_set)) {
echo "<li";
if ($subject["id"] == $sel_subject["id"]) { echo " class=\"selected\""; }
echo "><a href=\"contents.php?subj=" . urlencode($subject["id"]) .
"\">{$subject["menu_name"]}</a></li>";
$page_set = get_pages_for_subject($subject["id"]);
echo "<ul class=\"pages\">";
while ($page = mysql_fetch_array($page_set)) {
echo "<li";
if ($page["id"] == $sel_page["id"]) { echo " class=\"selected\""; }
echo "><a href=\"contents.php?pages=" . urlencode($page["id"]) .
"\">{$page["menu_name"]}</a></li>";
}
echo "</ul>";
}
?>
</ul>
</td>
<td id="page">
<?php if (!is_null($sel_subject)) { // subject selected ?>
<h2><?php echo $sel_subject['menu_name']; ?></h2>
<?php } elseif (!is_null($sel_page)) { // page selected ?>
<h2><?php echo $sel_page['menu_name']; ?></h2>
<div class="page-content">
<?php echo $sel_page['content']; ?>
</div>
<?php } else { // nothing selected ?>
<h2>Select a subject or page to edit</h2>
<?php } ?> </td>
</tr>
</table>
<?php require_once 'includes/footer.php';?>
Your 'N' is coming from the "NULL" string. I believe you meant to set your variables with actual NULL and not a string. Like:
$var = NULL;
As opposed to:
$var = "NULL";
When you access a variable that is set to "NULL" as an array, you will get the 'N' (as the string is treated as an array). For instance;
$var = "NULL";
echo $var[0]; // 'N'
Furthermore, if you test for NULL on a string it will return false (the variable is non-null);
$var = "NULL";
if($var) {
echo "var is: " . $var;
}
else {
echo "var is NULL!";
}
The above should output "var is: NULL".
I say this from experience (I did this when I started coding PHP). However, the root of your problem likely doesn't stop there as your variables should be set in subsequent conditionals. I would go through your while statements, and if statements and ensure your variables are being set appropriately. (var_dump($var) or print_r($var) through suspect blocks).
I have the code below that is selecting a random set of questions from Wordpress.
<?php
$rows = get_field('step_by_step_test');
$row_count = count($rows);
$rand_rows = array();
$questions = get_field('select_number_of_questions');
for ($i = 0; $i < min($row_count, $questions); $i++) {
$r = rand(0, $row_count - 1);
while (array_search($r, $rand_rows) !== false) {
$r = rand(0, $row_count - 1);
}
$rand_rows[] = $r;
echo $rows[$r]['question'];
}
?>
I want to incorporate a bit of extra code (below), how can I make sure it's selecting the same random question?
<?php if(get_sub_field('answer_options')): ?>
<?php while(has_sub_field('answer_options')): ?>
<?php echo the_sub_field('answer'); ?>
<?php endwhile; ?>
<?php endif; ?>
Why dont you change your approach slightly?
<?php
$rows = get_field('step_by_step_test'); // Get the test
$question_count = get_field('select_number_of_questions'); // Get the number of questions
$rows = shuffle($rows); // Randomize your questions
$rows = array_slice($rows, $question_count); // Now set the array to only contain the number of questions you wanted
foreach ($rows as $row) {
echo $row['question']; // Show the question
if(get_sub_field('answer_options', $row['id'])) {
while(has_sub_field('answer_options', $row['id'])) {
echo the_sub_field('answer');
}
}
}
?>
I made the assumption that you can alter "get_sub_field" to include the ID of the question, so you can then include the ID in your "where" field of "answer_options". This will allow you to link the question.
I think that what you need is to set up the whole thing in a loop. query by custom field
Or you could store the ids of the questions you got above, an then, below, query for the answers for those specific posts.
Here's how I randomized my WordPress slider using the Advanced Custom Fields plugin + Royal Slider with a modified version of TheSwiftExchange's code above
<div id="full-width-slider" class="royalSlider heroSlider rsMinW">
<?php
/*
* Slider Repeater field shuffled
* http://stackoverflow.com/questions/12563116/incorporating-extra-loop-into-random-selection
*/
$rows = get_field('slider');
// For Debugging:
// echo "<pre>";
// var_dump($rows);
// echo "</pre>";
$quotes = get_field('slide_text'); // Get the number of images
shuffle($rows); // Randomize your slides
foreach ($rows as $row) {
$slideImageID = $row['slide_image'];
$slideImage = wp_get_attachment_image_src( $slideImageID, 'full' );
$slideText = $row['slide_text'];
?>
<div class="rsContent">
<div class="royalCaption">
<div class="royalCaptionInner">
<div class="infoBlock">
<?php if(!empty($slideText)) {
echo $slideText;
}; ?>
</div>
</div>
</div>
<img src="<?php echo $slideImage[0]; ?>" class="" />
</div><!-- /.rsContent -->
<?php } // end foreach ?>
</div><!-- /slider-wrap -->