Home » Php » COUNT DISTINCT WHERE JOIN in one query php mysql

COUNT DISTINCT WHERE JOIN in one query php mysql

Posted by: admin February 25, 2020 Leave a comment

Questions:

I’m beginner in PHP,
How Making COUNT DISTINCT JOIN and Multiple WHERE in one query ?
for output to json

I tried

<?php
require_once "../conn.php";
$query = "SELECT
COUNT(DISTINCT tbl_trx.idoutlet WHERE (tbl_trx.payone != 0)) as p1
COUNT(DISTINCT tbl_trx.idoutlet WHERE (tbl_trx.paytwo != 0)) as p2
COUNT(DISTINCT tbl_trx.idoutlet WHERE (tbl_trx.paythree != 0)) as p3
FROM tbl_outlet
INNER JOIN tbl_trx ON tbl_trx.idoutlet = tbl_outlet.id
WHERE id = $_GET[id]";
$sql = mysqli_query ($link,$query);
$ray = array();
while ($row = mysqli_fetch_array($sql)) {
  array_push($ray, array(
    "payone" => $row['p1'],
    "paytwo" => $row['p2'],
    "paythree" => $row['p3'],
  ));
}
echo json_encode($ray);
mysqli_close($link);
?>

But Doesnt Work
Please Help

How to&Answers:

You should avoid php var is sql and use param and a case for filter

select  count ( DISTINCT CASE WHEN tbl_trx.payone != 0 THEN tbl_trx.idoutlet ELSE NULL END) p1
, count ( DISTINCT CASE WHEN tbl_trx.paytwo != 0 THEN tbl_trx.idoutlet ELSE NULL END) p2 
, count ( DISTINCT CASE WHEN tbl_trx.paythree != 0 THEN tbl_trx.idoutlet ELSE NULL END) p3 
FROM tbl_outlet
INNER JOIN tbl_trx ON tbl_trx.idoutlet = tbl_outlet.id
WHERE id = :id