Looping Through Database Query
I am creating a very simple script. The purpose of the script is to pull a question from the database and display all answers associated with that particular question. We are dealing with two tables here and there is a foreign key from the question database to the answer database so answers are associated with questions.
Hope that is enough explanation. Here is my code. I was wondering if this is the most efficient way to complete this or is there an easier way?
<html>
<head>
<title>Advise Me</title>
<head>
<body>
<h1>Today's Question</h1>
<?php
//Establish connection to database
require_once('config.php');
require_once('open_connection.php');
//Pull the "active" question from the datab开发者_StackOverflow中文版ase
$todays_question = mysql_query("SELECT name, question
FROM approvedQuestions
WHERE status = active")
or die(mysql_error());
//Variable to hold $todays_question aQID
$questionID = mysql_query("SELECT commentID FROM approvedQuestions
WHERE status = active")
or die(mysql_error());
//Print today's question
echo $todays_question;
//Print comments associated with today's question
$sql = "SELECT commentID FROM approvedQuestions WHERE status = active";
$result_set = mysql_query($sql);
$result_num = mysql_numrows($result_set);
for ($a = 0; $a < $result_num; $a++)
{
echo $sql;
}
?>
</body>
</html>
I Tlooks like youre not actually gabbing the question or comment text... dont know if thats an issue or not. Since there is only ever one question (????) i would jjoin all the comments to the question and do it that way:
$query = "SELECT q.*, c.* FROM approvedQuestions q LEFT JOIN comments c ON (q.id = c.questionID) WHERE q.status = 'active'";
$result = mysql_query($query);
if(mysql_num_rows()){
while(false !== ($row = mysql_fetch_assoc($result)){
// $row contains all columns for both question and record as array keys
echo $row['commentID'];
echo $row['id'];
echo $row['name'];
}
}
Not this would pront the question info everytime you print the answer info but that is easily solved by fetching the first ro before the loop and pulling the question data into another array, then rewinding the result set and invoking the loop.
精彩评论