tags:

views:

42

answers:

1

I have data in a sql database that'd I'd like to display on a simple website. The data has an initial question ID "IntQID", which is an auto increment field. Every post has an IntQID. There is another field called "ResID", which is the response ID for a post that is responding to a question. The only data that has no ResID is the initial question a user posts. What's i'm trying to do is write a php script that will pull that data and display it like so:

Question 1:
Answer 1
Answer 2
Answer 3
etc...

Question 2:
Answer 1
Answer 2
Answer 3
etc...

Etc.....

Additional Info: - ResID and IntQID are in the same Table

A: 

I believe this should do the trick for you. Just include the two functions below somewhere in the page, and then call showQuestionsAndResponses(); when you want to show the list. Obviously you'll probably want to adjust the echo statements to make it print everything in a more attractive manner.

function showQuestionsAndResponses() {
  $query = "SELECT * FROM my_table WHERE resID IS NULL";
  $sql_result = mysql_query($query);

  while ($row = mysql_fetch_array($sql_result) {
    echo $row['title'].": ".$row['text'];
    $responses = getResponses($row['IntQID']); //get responses for curr question
    foreach($responses as $response) {
      echo $response['text']; //print each response
    }
  }
}

function getResponses($qID) {
  if(is_numeric($qID) { //always best to check, just to be sure!
    $query = "SELECT * FROM my_table WHERE resID = ".$qID;
    $sql_result = mysql_query($query);
    $responses = array();
    while ($row = mysql_fetch_array($sql_result) {
      $responses[] = $row; //add current row to array
    }
    return $responses; //return the array of responses
  }
  return false; //return false by default
}
JGB146