如何避免MySQL查询结果重复?

时间:2019-03-16 13:10:06

标签: php mysql

我有一个PHP脚本从MySQL查询中获取行,但是,某些serum被多次显示。我希望每个serum仅显示一次。

<?php
$typeno = 0;
$categories = [];
$gettestcat = mysqli_query($con,"SELECT * from types where testid = '$id'");

while($gtc = mysqli_fetch_array($gettestcat)){
    $testid = $gtc['testtypeid'];
    $gettesttypename = mysqli_query($con,"SELECT * from tests where id = '$testid'");
    $gtyn = mysqli_fetch_array($gettesttypename);

    if (!in_array($gtyn['sample_type'], $categories)) {
        $categories [] = $gtyn['sample_type'];
    }
}

$countcat = count($categories);
$gettesttypes = mysqli_query($con,"SELECT * from types where testid = '$id'");

while($gtt = mysqli_fetch_array($gettesttypes)){
    $testid = $gtt['testtypeid'];
    $gettesttypenames = mysqli_query($con,"SELECT * from tests where id = '$testid'");
    $gtyns = mysqli_fetch_array($gettesttypenames);

    if ($gtyns['sample_type'] == 'Serum') {
        echo $gi['name'].' - '.$gtyns['test_name'].' - ';
    }
}
?>

<?php  ?>
<?php   
?>

enter image description here

我需要使它像图像上所示,名称只显示一次。

enter image description here

2 个答案:

答案 0 :(得分:2)

如果您使用mysql,请使用DISTINCT关键字以获得唯一的结果

答案 1 :(得分:0)

您可以将输出的名称存储在数组中。然后在回显它之前检查名称是否在数组中。

// Initialize the array
$names = [];

while($gtt = mysqli_fetch_array($gettesttypes)){
    $testid = $gtt['testtypeid'];
    $gettesttypenames = mysqli_query($con,"SELECT * from tests where id = '$testid'");
    $gtyns = mysqli_fetch_array($gettesttypenames);

    if ($gtyns['sample_type'] == 'Serum') {

        if (!array_key_exists($gi['name'], $names)) {
            // The name doesn't exist in the array, echo it:
            echo $gi['name'] . '-';

            // Put the name into the array so it won't be echoed again
            $names[$gi['name']] = true;
        }

        echo $gtyns['test_name'].' - ';
    }
}