2011-06-27 50 views
1

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

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

<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

为什么要进行3个不同的查询以获得同一行中的不同列?而且,在循环中,您正在有效地打印出您的SQL查询,而不是结果集。 – jerluc

+1

+1给jerluc,@DrakeNET,$ sql对我没有意义。 –

回答

0

我Tlooks像youre实际上并没有g the问题或评论文本...不知道这是否是一个问题。由于只有永远一个问题(????)我会jjoin所有评论的问题,这样做的:

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

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