Owen Percoco
Owen Percoco

Reputation: 593

How to pull from a database to make an FAQ page?

Alright, I have a Database with three tables. Q&A, Categories, and IDs. Categories holds categories, Q&A has the questions and answers, and IDs has the IDs of various categories and the questions attached to them. How can I pull from the database so that I get a category, and then a loop of the Q&A that falls into that category?

function print_categories() {
global $MySQL;


if (($categories = $MySQL->select_all("SELECT * FROM QandA_wiki.categories")) !== false) {
foreach ($categories as $citem) {
$counter = 1;
print"<div id=\"categories_start\" style=\"width:424px; margin:0 auto;\">\n";
print"<div id=\"category\" >\n";
print"<h2> {$citem['description']}</h2>";
print  "<div class=\"col-lg-12 footerLine\"><hr /></div>";
    if (($questions = $MySQL->select_all("SELECT * FROM QandA_wiki.qanda")) !== false) {
    foreach ($questions as $qitem) {
        print"<div id=\"question_number\" >\n";
        print"<div id=\"questions\" >\n";
        print"<p>#: {$counter} -<strong>{$qitem['question']}</strong></p>";

        print"</div>\n";
        print"<p>     {$qitem['answer']}</p>";
        print  "<div class=\"col-lg-12 footerLine\"><hr /></div>";


        print"</div>\n";

        print"<div style=\"clear:both;\"></div>\n";
        print"<br />\n";
        $counter=$counter+1;
        }
      }
print"</div>\n";
print"</div>\n";

print"<div style=\"clear:both;\"></div>\n";
print"<br />\n";

}}}}

Upvotes: 4

Views: 115

Answers (1)

camelCase
camelCase

Reputation: 5608

I'm not sure of your table/column names but this is a rough idea of a LEFT JOIN that might get what you need

SELECT QandA_wiki.qanda.*, QandA_wiki.qanda.id, QandA_wiki.qanda.name_of_your_column
FROM QandA_wiki.qanda
LEFT JOIN QandA_wiki.categories
ON QandA_wiki.qanda.category_id = QandA_wiki.categories.id // This is a guess here...likely will need to modify
WHERE QandA_wiki.categories.name_of_your_column = name_you_want; // This where clause does the filtering as you needed

Also, I'm not sure what your $MySQL function does but in mysqli it would look something like this (where $link is your database connection info):

$query = mysqli_query($link,
    "SELECT QandA_wiki.qanda.*, QandA_wiki.qanda.id, QandA_wiki.qanda.name_of_your_column
    FROM QandA_wiki.qanda
    LEFT JOIN QandA_wiki.categories
    ON QandA_wiki.qanda.category_id = QandA_wiki.categories.id
    WHERE QandA_wiki.categories.name_of_your_column = name_you_want;");

Then you can just iterate over $query. You should consider using prepared statements if you're grabbing the category via user input. I hope this gets you going in the correct direction

Upvotes: 1

Related Questions