繁体   English   中英

遍历数据库查询

[英]Looping Through Database Query

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

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

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

我看起来像是您实际上并未窃听问题或评论文本……不知道这是否是一个问题。 由于只有一个问题(????),所以我会将所有对该问题的评论都加入并以这种方式进行:

$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并将问题数据拉入另一个数组,然后倒退结果集并调用循环来轻松解决。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM