2015-01-10 33 views
-2

我只想打印沒有類似書名的書名和發佈者。使用PHP和MySQL獲取數據庫中的一些值

while($row_result_kinder1_comp_lit = mysqli_fetch_array($sql_result_kinder1_comp_lit)) { 
      $fetched1 = $row_result_kinder1_comp_lit[3]; //fetch booktitle column from  $sql_result_kinder1_comp_lit // 
      echo $fetched1; 
     } 
      while($row_kinder1_comp_lit = mysqli_fetch_array($sql_kinder1_comp_lit)) { 
      $fetched2 = $row_kinder1_comp_lit[1]; //fetch booktitle column column from  $sql_kinder1_comp_lit // 
     if($fetched1 != $fetched2) { 
    echo $row_kinder1_comp_lit['booktitle']; 
    echo $row_kinder1_comp_lit['publisher']; 
    } 
} 

問題是$ fetched1裏面if語句只獲取我數據庫中最後一行的值。因此,它只隱藏$ sql_kinder1_comp_lit中的書,並在$ result_sql_kinder1_comp_lit的最後一行顯示相同的書名;

my table $sql_kinder1_comp_lit is 
id booktitle publisher 
1  book1  publisher1 
2  book2  publisher2 
3  book3  publisher3 

my table $sql_result_kinder1_comp_lit is 
id booktitle publisher 
1  book1  publisher1 
2  book2  publisher2 

我只想顯示book3,因爲它沒有與其他表格相同的書目標題。

+0

爲什麼不只是在SQL查詢中獲取所需的項目?另外,我們不知道數據庫中有關表的任何信息。 –

+0

你可以移動}所以你的第二個在第一個?然後再次可能會更好的性能來保存數組中的值,這樣您就可以在第二時間內搜索該數組。 –

+0

@spencer,我這樣做是爲了達到目的,我不想將具有相同書名的行的書名和出版商展示給其他表格。對不起,我不知道如何更具體地瞭解我的問題。請參閱編輯。 –

回答

1

我已經把它貼的你怎麼可以用一個數組做一個例子,節省了什麼書名你已經看到並且沒有顯示已經存在於第一組書籍中的那些。

if語句檢查數組內是否有值,所以不需要使用數組的布爾值,但我覺得它更具描述性。

<?php 
    var $bookarray; 
    while($row_result_kinder1_comp_lit = mysqli_fetch_array($sql_result_kinder1_comp_lit)) { 
     $first_booktitle = $row_result_kinder1_comp_lit[3]; //fetch booktitle column from  $sql_result_kinder1_comp_lit // 
     $bookarray[$first_booktitle] = true; 
    } 

    while($row_kinder1_comp_lit = mysqli_fetch_array($sql_kinder1_comp_lit)) { 
     $second_booktitle = $row_kinder1_comp_lit[1]; //fetch booktitle column column from  $sql_kinder1_comp_lit // 
     if(!$bookarray[$second_booktitle]) { 
      echo $row_kinder1_comp_lit['booktitle']; 
      echo $row_kinder1_comp_lit['publisher']; 
     } 
    } 
?> 
+0

太棒了!這真的解決了我的問題。我很抱歉,因爲我現在無法支持你。非常感謝!!!!我只是刪除變種。 –

+0

自從我寫了PHP以來,一段時間過去了,但舊的腳本編寫方式很難被忽略。祝您的編碼順利。 –

0

它只做最後一個項目,因爲在開始比較之前,您要通過第一個結果中的所有項目。 mysqli_fetch_array將在第一個while循環中繼續,最後$fetched1將是查詢結果的最後一行。所有這些都發生在你開始查看下一個查詢之前。只要將}所以它不會關閉環路,並獲取$fetched1進行比較與所有項目從$fetched2

while($row_result_kinder1_comp_lit = mysqli_fetch_array($sql_result_kinder1_comp_lit)) { 
    $fetched1 = $row_result_kinder1_comp_lit[3]; //fetch booktitle column from  $sql_result_kinder1_comp_lit // 
    echo $fetched1; 

    while($row_kinder1_comp_lit = mysqli_fetch_array($sql_kinder1_comp_lit)) { 
    $fetched2 = $row_kinder1_comp_lit[1]; //fetch booktitle column column from  $sql_kinder1_comp_lit // 
     if($fetched1 != $fetched2) { 
      echo $row_kinder1_comp_lit['booktitle']; 
      echo $row_kinder1_comp_lit['publisher']; 
     } 
    } 
} 
相關問題