Search code examples
phpsqldatabasefor-looplivesearch

how to echo my data only once if there's many data in my database


this is my code

$sql = "select * from tbproduk where namaproduk LIKE '$produk%'";
$query = mysqli_query($con, $sql) or die("error $sql");
$num = mysqli_num_rows($query);
$result = mysqli_fetch_array($query);
for ($x = 1; $x <= $num; $x++) {
    $namaproduk = $result['namaproduk'];
    echo "<button style='color: black;text-align: left'><a style='padding: 0;line-height: 0;color: black;background: none' href='Konfirmasi/index4.php?produk=$namaproduk'>".$namaproduk ."</a></button><br>";
}

as you can see, it will echo all data in my database but i have the same data name in database. This is my database data. this is my database data

so when it's echo it will be like this
result

how to loop my code once if there's the same data.


Solution

  • You need to select distinct records from data base. change your query as below:

    $sql = "select DISTINCT namaproduk from tbproduk where namaproduk LIKE '$produk%'";