使用PHP和MySQL从数据库中获取时无法避免重复数据

时间:2015-11-28 06:14:23

标签: php mysql

我有一个问题。使用PHP和MySQL从数据库中检索时,我无法避免重复数据。我正在解释下面的代码。

   <?php
require_once '../../include/dbconfig.php'; 
$postdata = file_get_contents("php://input");
$request = json_decode($postdata);
$colg_id=$request->colg_id;
$result = mysqli_query($connect, "SELECT DISTINCT dept_id  from db_unit_plan where clg_id='".$colg_id."'  ");
if($row =mysqli_fetch_assoc($result)) {
    //$dept_id = $row[dept_id]; 
    //$result = mysqli_query($connect, "select *  from db_department where colg_id='".$colg_id."' and dept_id='".$dept_id."'  ");
    $data = array();
    while ($row =mysqli_fetch_assoc($result)) {
        $data[] = $row;
    }

print json_encode($data);
}
?>

这里db_unit_plan表中有很多行有相同的dept_id.Here我需要避免重复的数据。请帮助我。

1 个答案:

答案 0 :(得分:1)

<?php
require_once '../../include/dbconfig.php'; 
$postdata = file_get_contents("php://input");
$request = json_decode($postdata);
$colg_id=$request->colg_id;
$result = mysqli_query($connect, "SELECT DISTINCT dept_id FROM db_unit_plan where clg_id='".$colg_id."'  ");

$data = array();
while ($row = mysqli_fetch_assoc($result)) {
    $data[] = $row['dept_id'];
}

print json_encode($data);

修改

如果您需要结果中唯一的db_department列表:

<?php
require_once '../../include/dbconfig.php'; 
$postdata = file_get_contents("php://input");
$request = json_decode($postdata);
$colg_id=$request->colg_id;
$result = mysqli_query($connect, "SELECT DISTINCT db_department.*  
    FROM db_department 
    JOIN db_unit_plan ON db_unit_plan.dept_id = db_department.dept_id
    WHERE db_unit_plan.clg_id='".$colg_id."'  ");

$data = array();
while ($row = mysqli_fetch_assoc($result)) {
    $data[] = $row;
}

print json_encode($data);