循环数据库查询

时间:2011-06-27 06:06:05

标签: php mysql for-loop

我正在创建一个非常简单的脚本。该脚本的目的是从数据库中提取问题并显示与该特定问题相关的所有答案。我们在这里处理两个表,从问题数据库到答案数据库有一个外键,所以答案与问题相关。

希望这是足够的解释。这是我的代码。我想知道这是否是最有效的方法来完成这个还是有更简单的方法吗?

<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 database
    $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>

1 个答案:

答案 0 :(得分:0)

我看起来好像你实际上没有唠叨问题或评论文字......不知道那是不是问题。由于只有一个问题(????),我会在问题的所有评论中加入并按照这样做:

$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'];
  }
}

每次打印答案信息时,这都不会引发问题信息,但通过在循环之前获取第一个ro并将问题数据拉入另一个数组,然后倒回结果集并调用循环,可以轻松解决问题。