I have a working survey that pulls each question and any related answers from multiple tables. Each question is stored in the following table:
tblQuestions, with the fields:
qID
qText.
The related answers are stored in the table:
tblPossAnswers, with the fields:
aID
qID
answerText.
So, I would have 3 possible answers for each question. My sql to pull everything is:
select * from tblQuestions, tblPossAnswers where
tblPossAnswers.qID = tblQuestions.qID
order by tblQuestions.qID ASC
And my PHP to display it:
while ($row = mysql_fetch_array($result)) {
echo "<p>" . $row['qText'] . "</p><br />";
echo "<input type='radio' name='".$row['qID']."' value='".$row['aID']."' />";
echo $row['answerText'];
}
The problem is this is displaying the qText every time it displays a possible answer. So it looks like:
Question 1
Possible answer 1
Question 1
Possible answer 2
Question 1
Possible answer 3
Question 2
Possible answer 1
Question 2
Possible answer 2
Question 2
Possible answer 3
What I would like to do is have the qText only display when the first possible answer is pulled. I'm still somewhat of a newb to MySQL, so the solution might be something very simple that I'm just not seeing.
You can either test for whether the question has changed within your PHP loop:
while ($row = mysql_fetch_array($result)) {
if ($row['qID'] != $lastQuestionID) {
echo "<p>" . $row['qText'] . "</p><br />";
$lastQuestionID = $row['qID'];
}
echo "<input type='radio' name='".$row['qID']."' value='".$row['aID']."' />";
echo $row['answerText'];
}
Or else you can group the MySQL results by question using GROUP_CONCAT, specifying a separator on which you then split the answers in PHP:
select *, group_concat(answerText separator char(30)) as answers
from tblQuestions join tblPossAnswers using (qID)
group by tblQuestions.qID
order by tblQuestions.qID ASC
Then:
while ($row = mysql_fetch_array($result)) {
echo "<p>" . $row['qText'] . "</p><br />";
foreach (explode(chr(30), $row['answers']) as $answer) {
echo "<input type='radio' name='".$row['qID']."' value='".$answer."' />";
echo $answer;
}
}
No need to change anything in sql just change php slightly as following
while ($row = mysql_fetch_array($result)) {
if ($row['qText'] != $lastQuestion) {
echo "<p>" . $row['qText'] . "</p><br />";
$lastQuestion = $row['qText'];
}
echo "<input type='radio' name='".$row['qID']."' value='".$row['aID']."' />".$row['answerText'];
}
Related
This question already has answers here:
How do I iterate over the results in a MySQLi result set?
(2 answers)
Closed 5 months ago.
I'm very new to PHP and I'm trying to get some code that someone else has written to work. As the title says it is only showing the first result when it should be displaying many and I have no idea how to sort it (even though I imagine it's quite simple!). The code is below:
$result = mysqli_query($connection, ("SELECT id FROM details where publicposition like '%$trimvar%' or familyorgname like '%$trimvar%' or commercialorgind like '%$trimvar%' ORDER BY id "));
if (!$result)
{
die('Could not run query');
}
echo "<h1>Your staff conflict search on <font color='#ff0000'>'$trimvar'<font color='#000'> returned <font color='#ff0000'>$rows<font color='#000'> results</h1>";
$row = mysqli_fetch_array($result, MYSQLI_ASSOC);
{
echo "<table style='width: 20%; border='0';'>";
echo "<tr>";
echo "<th> Record ID : " . $row['id'] . "</th><br/>";
echo "</tr>";
}
echo "</table>";
Any help on this would be hugely appreciated!
mysqli_result::fetch_array -- mysqli_fetch_array — Fetch the next row
of a result set as an associative, a numeric array, or both
Try using mysqli_fetch_array inside a while loop to fetch one row at a time until the end is reached.
while ($row = mysqli_fetch_array($result,MYSQLI_ASSOC)) {
echo "<tr>";
echo "<th> Record ID : " . $row['id'] . "</th>";
echo "</tr>";
}
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;
}
}
}
I'm trying to make a quiz form which displays questions and 3 answers which are taken from my database. When I run my loop, it displays all the questions and answer choices correctly with the radio button but when I click on question 1 answer "b" then click question 2 answer "c" the radio button un-clicks question 1's answer "b" and highlight question 2 answer "c";
Answering question 1 Trying to answer question 2 after answering question 1
1. What is your name? 1. What is you name?
()John ()John
(*)Jake ()Jake <--un-clicked
()Joe ()Joe
2. Where are you from? 2. Where are you from?
()San Antonio ()San Antonio
()Austin ()Austin
()New York (*)New York
If you notice question 1 answer is removed when question 2 is answered.
Here is my code that retrieves the data from the database and displays it.
$mysql = "SELECT * FROM $table WHERE $table.quiz_name = '$name'";
$mydata = mysql_query($mysql,$con);
//post quiz name (here)
echo $name."</br>";
while($records = mysql_fetch_array($mydata)){
echo "<div>";
echo $records['question_description']."<br>";
//image displayed here
echo "<label><input type='radio' name='option' value=".$records['option_a'].">".$records['option_a']."</label><br>";
echo "<label><input type='radio' name='option' value=".$records['option_b'].">".$records['option_b']."</lable><br>";
echo "<label><input type='radio' name='option' value=".$records['option_c'].">".$records['option_c']."</label><br>";
echo "</ br> <hr>";
echo "</div>";
}
I hope someone can help me solve this issue.
you are grouping all radio buttons with 'option'... do this;
$counter = 0 //declare a counter outside the loop
and add this with the name
name='option".$counter."'
and increment counter inside the loop
$counter++
This will give you a group for each set of radio buttons
Your radio buttons need different names. Having them all with the same name will mean you can only select one out of every radio you have.
Your radio buttons should have a different name for each question. Consider using something like your database ID like so:
while($records = mysql_fetch_array($mydata)) {
echo $records['question_description']."<br>";
echo "<label><input type='radio' name='option" . $record['id'] . "' value=".$records['option_a'].">".$records['option_a']."</label><br>";
echo "<label><input type='radio' name='option" . $record['id'] . "' value=".$records['option_b'].">".$records['option_b']."</lable><br>";
echo "<label><input type='radio' name='option" . $record['id'] . "' value=".$records['option_c'].">".$records['option_c']."</label><br>";
}
Here is my piece of code:
$a=mysql_query("SELECT denumire_intrebare,denumire_varianta,tip_intrebare
FROM intrebari,variante
WHERE intrebari.cod_chestionar='".$_SESSION['cod']."'
AND intrebari.cod_intrebare=variante.cod_intrebare");
while($b=mysql_fetch_array($a))
if($b['tip_intrebare']==3)
{
echo $b['denumire_intrebare'];
echo "<br>";
echo "<input type='checkbox' name='option1' value='Milk'>";
echo $b['denumire_varianta'];
echo "<br>";
}
So let me explain. I query the database and it brings me up a question and the answers that are related to it. I want the answers to put them as checkbox answers. The problem is that my question is repeating for all the answers. So if i have 5 answers then the question appears 5 times like this: question answer1, question answer2, ... . I want my question to appear only once with the answers under the question. I'm missing something but I don't know what. Any help?
Make an array with all $b['denumire_varianta'] and use a foreach() after the while has finished, also make your checkboxes array so you can get them afterwards:
$variante = array();
while($b=mysql_fetch_array($a)) {
if($b['tip_intrebare']==3){
$intrebare = $b['denumire_intrebare'];
$variante[] = $b['denumire_varianta'];
}
}
echo $intrebare."<br />";
foreach($variante as $varianta){
echo "<input type='checkbox' name='option[]' value='".$varianta."'>";
echo $varianta."<br />";
}
I've spent the last few days wrestling with a MYSQL query issue. I hope someone can point me in the right direction.
I'm querying two tables ('questions' and 'comments') with the goal of returning the following layout:
Question 1
Comment 1
Comment 2
Comment 3
Question 2
Comment 4
Comment 5
And so on...
Comments are unique to a question (i.e. comments live under a parent question).
My query (which I know is incorrect) looks like this:
<?php
$query = "SELECT discussion.*, comments.* FROM discussion LEFT JOIN comments ON discussion.referenceID = comments.commentID";
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array($result)){
echo $row['question']. " - ". $row['comment']. "<br /><br />";
}
?>
The result:
Question 1 - Comment 1
Question 1 - Comment 3
Question 2 - Comment 2
I'm close, but can't achieve the multiple comments under the single question. I tried a 'GROUP BY discussion.question' but that limited my results to:
Question 1 - Comment 1
Question 2 - Comment 2
To put it in context I'm trying to allow users to submit comments on multiple questions displayed on a single page.
Thanks in advance.
RR
try this:
$query = "SELECT *
FROM discussion, comments
WHERE discussion.referenceID = comments.commentID
GROUP BY discussion.referenceID;
Just store the previous question and compare it to the current.
Sketch:
$prev_question = null;
while($row = mysql_fetch_array($result)) {
if ($prev_question != $row['question']) {
echo '<b>' . $row['question'] . '<b><br />';
$prev_question = $row['question'];
}
echo $row['comment'] . '<br />';
}
Zerkms, brilliant! Thanks for the response. Works perfectly, aside from one issue.
The questions only appear if there is a comment associated (an issue I caused myself, at some point). The goal is to display all comments regardless of if comments are assigned.
Working code:
<?php
$query = "SELECT discussion.*, comments.* FROM discussion LEFT JOIN comments ON discussion.referenceID = comments.commentID";
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array($result)){
$prev_question = null;
while($row = mysql_fetch_array($result)) {
if ($prev_question != $row['question']) {
echo "<h3>" . $row['question'] . "</h3>";
$prev_question = $row['question'];
}
echo "<img src=\"images/bg_addform_topFull.gif\" width=\"446\" height=\"11\" /><div class=\"comment\"><h3>" . $row['author'] . "</h3><div class=\"greyText\">" . $row['dt'] . "</div><p>" . $row['comment'] . "</p></div><img src=\"images/bg_addform_bottom.gif\" width=\"446\" height=\"11\" class=\"footerImage\" />";
}
}
?>
Again, thanks for the help.