2017-09-21 73 views
1

我的數據庫如何獲得獨特的價值在數組中的PHP

Tables_sup | 
+------------------+ 
| supid   |     
    scompany  | 
| scategory  | 
| smarket   | 
|  

我的PHP代碼

<?php 
require_once 'DBConnect.php'; 



    $con = mysqli_connect("localhost","gb","123"); 
     if (!$con) { 
     die('Could not connect: ' . mysqli_error()); 
     } 

    mysqli_select_db($con,"test_database"); 



    $sql=mysqli_query($con,'SELECT DISTINCT sup.supid,sup.smarket FROM sup order by supid desc'); 
    $i=0; 
    $dyn_table='<table border="1" cellpadding="10">'; 
    while($row=mysqli_fetch_array($sql)){ 

    $supid = $row["supid"]; 
    $smarket = $row["smarket"]; 

    if ($i%5==0){ 

     $dyn_table.='<tr><td>'.$smarket. '<td>'; 

     }else{ 

     $dyn_table.='<td>'.$smarket. '<td>'; 

    } 
    $i++; 
} 

$dyn_table.= '<tr><table>' ; 
?> 

我的HTML

<!DOCTYPE html> 
<html> 
<head> 
</head> 
<body> 
    <?php echo $dyn_table;?> 

</body> 
</html> 

我的問題 結果是OK,但有重複。如何獲得獨特的結果?

+1

你應該檢查[array_unique](http://php.net/manual/en/function.array-unique.php) –

+5

選擇不同的返回只有不重複所以...更新你的問題與數據採樣。,你的實際結果和預期結果 – scaisEdge

+1

你期望的結果是什麼? – Shibon

回答

1

假設您的sup表的id列是主鍵,因此無論如何都是唯一的,您的獨特查詢沒有任何意義 - 每個找到的結果都有不同的id,因此它可以使用相同的smarket返回多行。

查詢的不同smarket(不supid),你會得到你想要的結果集

SELECT DISTINCT smarket FROM sup 

我看到你tableconstruction一些錯誤,以及(收盤例如TR標籤)

// every fifth row is gonna be different? 
if ($i%5==0){ 
    $dyn_table.='<tr class="fifthrow"><td>'.$smarket. '</td></tr>'; 
}else{ 
    $dyn_table.='<tr><td>'.$smarket. '</td></tr>'; 
} 

和最後,不要打開另一個TR和表;)$dyn_table.= '</table>' ;

編輯:忘了補充一些結束標記爲表

+0

thanks.it作品 –

1

在您的情況下,您可以嘗試group by功能。