Go Back   CodingForums.com > :: Server side development > MySQL

Before you post, read our: Rules & Posting Guidelines

Reply
 
Thread Tools Rate Thread
Enjoy an ad free experience by logging in. Not a member yet? Register.
Old 11-29-2012, 07:58 PM   PM User | #1
m2244
Regular Coder

 
Join Date: Jun 2012
Posts: 129
Thanks: 1
Thanked 1 Time in 1 Post
m2244 is an unknown quantity at this point
How to list questions and asociated answers

Hello,

I am trying to get a list of questions stored in a table. There is a second table that has the related answers. When I run the following query I only get the questions, each one listed a numer of times.

How can I list each question once followed by all of the answers for that question?

Code:
select name from mp_question A
inner join mp_question_answers B
on A.category = B.question
where A.category = 107
m2244 is offline   Reply With Quote
Old 11-29-2012, 09:15 PM   PM User | #2
KULP
Regular Coder

 
Join Date: Mar 2012
Posts: 166
Thanks: 5
Thanked 11 Times in 11 Posts
KULP is an unknown quantity at this point
Here is what came to mind for me.

Code:
$allQuestions = mysql_query("SELECT * FROM questions", $connection );

while($oneQuestion = mysql_fetch_array($allQuestions))
{
      echo $oneQuestion["question_text"];
      $allAnswers = //Select everything from answer table with questionID

      while($oneAnswer = mysql_fetch_array($allAnswers)
      {
              echo $oneAnswer["answer_text"];
       }
}
KULP is offline   Reply With Quote
Old 11-29-2012, 10:21 PM   PM User | #3
Old Pedant
Supreme Master coder!

 
Old Pedant's Avatar
 
Join Date: Feb 2009
Posts: 23,556
Thanks: 62
Thanked 4,055 Times in 4,024 Posts
Old Pedant is a name known to allOld Pedant is a name known to allOld Pedant is a name known to allOld Pedant is a name known to allOld Pedant is a name known to allOld Pedant is a name known to all
Well, for starters, you need to SELECT the appropriate columns from the two tables.
Code:
SELECT A.name, B.answerText 
FROM mp_question A INNER JOIN mp_question_answers B
on A.category = B.question
where A.category = 107
But this seems weird to me: Why would you match the value of B.question with the value of A.category???

Maybe you need to show us your schema? All the fields in both tables?
__________________
An optimist sees the glass as half full.
A pessimist sees the glass as half empty.
A realist drinks it no matter how much there is.
Old Pedant is offline   Reply With Quote
Old 11-29-2012, 10:22 PM   PM User | #4
Old Pedant
Supreme Master coder!

 
Old Pedant's Avatar
 
Join Date: Feb 2009
Posts: 23,556
Thanks: 62
Thanked 4,055 Times in 4,024 Posts
Old Pedant is a name known to allOld Pedant is a name known to allOld Pedant is a name known to allOld Pedant is a name known to allOld Pedant is a name known to allOld Pedant is a name known to all
Oh...and except for a very very few odd circumstances, *NEVER* nest one query inside of another, as you did in your second post. HORRIBLY expensive!
__________________
An optimist sees the glass as half full.
A pessimist sees the glass as half empty.
A realist drinks it no matter how much there is.
Old Pedant is offline   Reply With Quote
Old 11-30-2012, 05:22 AM   PM User | #5
KULP
Regular Coder

 
Join Date: Mar 2012
Posts: 166
Thanks: 5
Thanked 11 Times in 11 Posts
KULP is an unknown quantity at this point
Quote:
Originally Posted by Old Pedant View Post
Oh...and except for a very very few odd circumstances, *NEVER* nest one query inside of another, as you did in your second post. HORRIBLY expensive!
Are you referring to my post (I'm the 2nd post) or his? If mine, how would you go around it?
KULP is offline   Reply With Quote
Old 11-30-2012, 02:56 PM   PM User | #6
Fou-Lu
God Emperor


 
Fou-Lu's Avatar
 
Join Date: Sep 2002
Location: Saskatoon, Saskatchewan
Posts: 15,741
Thanks: 4
Thanked 2,465 Times in 2,434 Posts
Fou-Lu is a name known to allFou-Lu is a name known to allFou-Lu is a name known to allFou-Lu is a name known to allFou-Lu is a name known to allFou-Lu is a name known to all
You use joins and let the software structure accordingly.
If you do a query within a loop, it would execute the query for the number of loops. If you had 60 questions, that means you would loop the inner query 60 times which is very expensive.
Pedant's first post there shows the join in question (with the ambiguity of the columns on the join mentioned).

So if I had a questions, and options table (so I could create a radio group for example), that would be similar to so using PHP to format it:
PHP Code:
$sQry 'SELECT q.questionID, q.questionDescription, qo.optionID, qo.option
            FROM question q
            INNER JOIN questionoption qo ON qo.questionID = q.questionID
            ORDER BY q.questionID ASC'
;
if (
$qry mysql_query($sQry))
{
    
$iLast = -1;
    if (
mysql_num_rows($qry) > 0)
    {
        while (
$row mysql_fetch_assoc($qry))
        {
            if (
$row['questionID'] != $iLast)
            {
                
// question has changed
                
if ($iLast > -1)
                {
                    print 
'</select>';
                }
                
$iLast $row['questionID'];
                
printf('<label for="question_%d">%s</label>'$iLast$row['questionDescription']);
                
printf('<select name="question_%d" id="question_%d">'$iLast$iLast);
            }
            
printf('<option value="%s">%s</option>'$row['optionID'], $row['option']);
        }
        print(
'</select>');
    }

I think I biffed the HTML in there, but that should give you the idea.
Fou-Lu is offline   Reply With Quote
Old 11-30-2012, 08:44 PM   PM User | #7
Old Pedant
Supreme Master coder!

 
Old Pedant's Avatar
 
Join Date: Feb 2009
Posts: 23,556
Thanks: 62
Thanked 4,055 Times in 4,024 Posts
Old Pedant is a name known to allOld Pedant is a name known to allOld Pedant is a name known to allOld Pedant is a name known to allOld Pedant is a name known to allOld Pedant is a name known to all
Well, aside from the fact that you said you were going to use radio buttons and then changed to use a <select>, it looks right to me. Even with my limited knowledge of PHP.
__________________
An optimist sees the glass as half full.
A pessimist sees the glass as half empty.
A realist drinks it no matter how much there is.
Old Pedant is offline   Reply With Quote
Old 11-30-2012, 09:16 PM   PM User | #8
Fou-Lu
God Emperor


 
Fou-Lu's Avatar
 
Join Date: Sep 2002
Location: Saskatoon, Saskatchewan
Posts: 15,741
Thanks: 4
Thanked 2,465 Times in 2,434 Posts
Fou-Lu is a name known to allFou-Lu is a name known to allFou-Lu is a name known to allFou-Lu is a name known to allFou-Lu is a name known to allFou-Lu is a name known to all
Quote:
Originally Posted by Old Pedant View Post
Well, aside from the fact that you said you were going to use radio buttons and then changed to use a <select>, it looks right to me. Even with my limited knowledge of PHP.
Lols I wonder if that's what I was thinking of when I said I think I biffed the HTML. I knew something didn't look quite right. Something still doesn't look quite right though :P; I have a feeling there will be possible outcomes that could leave tags orphaned somewhere.
Fou-Lu is offline   Reply With Quote
Old 11-30-2012, 09:41 PM   PM User | #9
Old Pedant
Supreme Master coder!

 
Old Pedant's Avatar
 
Join Date: Feb 2009
Posts: 23,556
Thanks: 62
Thanked 4,055 Times in 4,024 Posts
Old Pedant is a name known to allOld Pedant is a name known to allOld Pedant is a name known to allOld Pedant is a name known to allOld Pedant is a name known to allOld Pedant is a name known to all
I don't think so. I use essentially the same coding in ASP and it works.

Well, you probably want to slip a <br/> or <br/><br/> in there somewhere.

Either just before the <label> or just after the </select>.

But other than that...
__________________
An optimist sees the glass as half full.
A pessimist sees the glass as half empty.
A realist drinks it no matter how much there is.
Old Pedant is offline   Reply With Quote
Old 12-02-2012, 05:08 AM   PM User | #10
KULP
Regular Coder

 
Join Date: Mar 2012
Posts: 166
Thanks: 5
Thanked 11 Times in 11 Posts
KULP is an unknown quantity at this point
Can you explain how JOINs work?

I think I understand the syntax of this, but how does this store in $sQry? Is this a 2D array? In other words, how do I access each value? Sorry, this is probably a stupid question. Also, did you memorize how to write this off the top of your head?

PHP Code:
$sQry 'SELECT q.questionID, q.questionDescription, qo.optionID, qo.option
            FROM question q
            INNER JOIN questionoption qo ON qo.questionID = q.questionID
            ORDER BY q.questionID ASC'

EDIT: I tried this in my own project and I get the error:
Code:
Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given in C:\xampp\htdocs\Simpolls\user.php on line 37
I have tables: users, polls, and choices. Polls contains userid, and choices contains pollid. I'm trying to get all polls with userid $currentid and then join those results with the choices for each poll (pollid). 'date' is a timestamp value in my polls table, if that sounds right. Hmm...
PHP Code:
$result mysql_query('SELECT *
                FROM polls p WHERE p.userid = "' 
$currentid '" 
                INNER JOIN choices c ON c.pollid = p.pollid
                ORDER BY p.date DESC'
$connection);
                
                while(
$row mysql_fetch_array($result))
                {
                    echo 
$row['question'];
                } 

Last edited by KULP; 12-02-2012 at 09:03 AM..
KULP is offline   Reply With Quote
Old 12-02-2012, 09:31 PM   PM User | #11
KULP
Regular Coder

 
Join Date: Mar 2012
Posts: 166
Thanks: 5
Thanked 11 Times in 11 Posts
KULP is an unknown quantity at this point
I finally got the query to work after an hour or two of messing with it / research! Now I have it echoing the question and first choice, but how do I access choice 2 (I have 2 choices in the choice table, both with pollid as 1.) This works, but does it look right? I just feel weird fetching an array inside of an array.
PHP Code:

                $qry 
'SELECT * FROM polls
                INNER JOIN choices ON polls.id = choices.pollid
                WHERE polls.userid = 1000'
;
                
                
$result mysql_query($qry$connection);
                
                if(
$result === FALSE)
                {
                    die(
mysql_error()); 
                }

                while(
$row mysql_fetch_array($result))
                {
                    echo 
$row['question'];
                    echo 
$row['choice'];
                    
                    while(
$row mysql_fetch_array($result))
                    {
                        echo 
$row['choice'];
                    }
                } 
/////////////////////////////////////////////////////////////////////

EDIT x12312 :

Nevermind I figured it out, so far!

Last edited by KULP; 12-03-2012 at 12:24 AM..
KULP is offline   Reply With Quote
Reply

Bookmarks

Jump To Top of Thread


Thread Tools
Rate This Thread
Rate This Thread:

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off

Forum Jump


All times are GMT +1. The time now is 01:41 PM.


Advertisement
Log in to turn off these ads.