2014-02-25 208 views
0

我的if語句在我的while循環中似乎無法正確執行。我認爲這可能與我的邏輯有關。對我來說,它似乎應該工作,但一定有一些我錯過了。我需要While循環來運行並且每次都進行計數。在第四個循環中,我需要if語句中的代碼運行,但似乎永遠不會發生。任何人都可以提供soloution嗎?PHP IF ELSE語句問題

<?php 
    $input = $_GET['input'];//Note to self $input in the name of the search feild 
    $terms = explode(" ", $input); 
    $query = "SELECT * FROM content WHERE "; 

    foreach ($terms as $each){ 
     $i++; 
     if ($i == 1) 
      $query .= "keywords LIKE '%$each%' "; 
     else 
      $query .= "OR keywords LIKE '%$each%' "; 
    } 

    // connecting to our mysql database 
    mysql_connect("localhost", "username", "password"); 
    mysql_select_db("database"); 

    $query = mysql_query($query); 
    $numrows = mysql_num_rows($query); 

    if ($numrows > 0){ 
     for($i=0; $i < $numrows; $i++){ 
     while ($row = mysql_fetch_assoc($query)){ 

      $id = $row['id']; 
      $title = $row['title']; 
      $description = $row['description']; 
      $keywords = $row['keywords']; 
      $link = $row['link']; 
      $plink = $row ['plink']; 
      $views = $row ['views']; 

       if($i== 4){ 
      echo '<td valign="top" "width="248" height="100%"> 
      <table width="100%" border="0"> 
      <tr> 
       <td align="center" valign="top"><a href='.$link.'> 
       <img src='.$plink.'width="200" height="151" vspace="5" /> 
      <br><b><a href='.$link.'>'.$title.'</b></a> 
       <br><strong><span style="line-height:20px">Total views: '.$views.'</span></strong> 
       </td> 
        </tr> 
       </table> 
       </td><tr>';    
      } 

      else{ 

      echo '<td valign="top" "width="248" height="100%"> 
      <table width="100%" border="0"> 
      <tr> 
       <td align="center" valign="top"><a href='.$link.'> 
       <img src='.$plink.'width="200" height="151" vspace="5" /> 
      <br><b><a href='.$link.'>'.$title.'</b></a> 
       <br><strong><span style="line-height:20px">Total views: '.$views.'</span></strong> 
       </td> 
        </tr> 
       </table>' 
          ; 

       } 
        } 


     } 



     } 

    else 
     echo "No results found for \"<b>$input</b>\""; 



    // disconnect 
    mysql_close(); 
?> 
+1

您的應用程序容易受到SQL注入...... – Tobias

+0

真的,我該如何解決呢? – user3349271

+0

請參閱http://www.php.net/manual/en/function.mysql-real-escape-string.php,您需要轉義所有來自腳本外部的輸入。 – Tobias

回答

0

您正在爲每行循環一次,但在for循環中,您有一段時間正在獲取所有行。你需要擺脫for循環。

因此,而不是這樣做:

for($i=0; $i < $numrows; $i++){ 
    while ($row = mysql_fetch_assoc($query)){ 

你應該這樣做:

$i = 0; 
    while ($row = mysql_fetch_assoc($query)){ 
     $i++; 
     .... 
+0

我喜歡你的朋友。這是問題所在。非常感激,非常感謝。 – user3349271

+0

如果它的工作接受和upvote答案,請 – ElefantPhace

0

在您for$i == 1的第一次迭代,所以你的病情將不會執行。但是,您的while循環將清空結果集,以便在for循環的第二次和後續迭代中不會提取任何行。您的if條件不會再次遇到。