2010-05-07 61 views
0

为什么这只打印第一个网站下的网站特定内容,而不是为其他2打印?PHP/MySQL问题

<?php 
     echo 'NPSIN Data will be here soon!'; 

     // connect to DB 
     $dbhost = 'localhost'; 
     $dbuser = 'root'; 
     $dbpass = 'root'; 

     $conn = mysql_connect($dbhost, $dbuser, $dbpass) or die ('Error connecting to DB'); 

     $dbname = 'npsin'; 

     mysql_select_db($dbname); 

     // get number of sites 
     $query = 'select count(*) from sites'; 
     $result = mysql_query($query) or die ('Query failed: ' . mysql_error()); 

     $resultArray = mysql_fetch_array($result); 
     $numSites = $resultArray[0]; 

     echo "<br><br>"; 

     // get all sites 
     $query = 'select site_name from sites'; 
     $result = mysql_query($query); 

     // get site content 
     $query2 = 'select content_name, site_id from content'; 
     $result2 = mysql_query($query2); 

     // get site files 


     // print info 
     $count = 1; 
     while ($row = mysql_fetch_array($result, MYSQL_NUM)) { 
       echo "Site $count: "; 
       echo "$row[0]"; 
       echo "<br>"; 
       $contentCount = 1; 
       while ($row2 = mysql_fetch_array($result2, MYSQL_NUM)) { 
         $id = $row2[1]; 
         if ($id == ($count - 1)) { 
           echo "Content $contentCount: "; 
           echo "$row2[0]"; 
           echo "<br>"; 
         } 

         $contentCount++; 
       } 

       $count++; 
     } 
?> 

回答

2

的问题是,您认为一旦你完成了寻找具有相同id作为该网站鳞次栉比,它会重置$result2查询到开头。这意味着在找到第一行之后(除非要对这两个查询进行排序),那么while循环的第二遍将不会有任何结果。你应该考虑首先缓存内部while循环,然后使用数组查找来获取值。

一个更好的解决方案将涉及从sitescontent的连接,这将不需要这个复杂的匹配过程。连接是SQL的一个非常重要的部分,我强烈建议学习如何使用它们。 http://dev.mysql.com/doc/refman/5.0/en/join.html