如何简化这些mySQLi查询?

时间:2015-12-09 18:41:22

标签: php mysqli

我有5个类似的查询输出一个数字。 payment_type确定输出。基本上它将显示当年使用现金,支票,信用卡或自动转账完成的交易次数。

$getTxnX = $con->query("SELECT COUNT(*) AS num FROM transaction WHERE YEAR(paid_on) LIKE '%".date ('Y')."%'");
$getTxnC = $con->query("SELECT COUNT(*) AS num FROM transaction WHERE YEAR(paid_on) LIKE '%".date ('Y')."%' AND payment_type='C'");
$getTxnK = $con->query("SELECT COUNT(*) AS num FROM transaction WHERE YEAR(paid_on) LIKE '%".date ('Y')."%' AND payment_type='K'");
$getTxnO = $con->query("SELECT COUNT(*) AS num FROM transaction WHERE YEAR(paid_on) LIKE '%".date ('Y')."%' AND payment_type='O'");
$getTxnA = $con->query("SELECT COUNT(*) AS num FROM transaction WHERE YEAR(paid_on) LIKE '%".date ('Y')."%' AND payment_type='A'");

我正在使用

输出数字
if ( $row = $getTxnX->fetch_assoc() ) { 
    echo $row['num']; 
}
if ( $row = $getTxnC->fetch_assoc() ) { 
    echo $row['num']; 
}
if ( $row = $getTxnK->fetch_assoc() ) { 
    echo $row['num']; 
}
if ( $row = $getTxnO->fetch_assoc() ) { 
    echo $row['num']; 
}
if ( $row = $getTxnA->fetch_assoc() ) { 
    echo $row['num']; 
}

它运行正常,但有没有办法将查询简化为一个,然后使用类似下面的内容?:

if ( $row = $getNewTxnQueryHere->fetch_assoc() ) { 
    echo $row['X']; 
    echo $row['C']; 
    echo $row['K']; 
    echo $row['O']; 
    echo $row['A']; 
}

我计划将if ( $row = $getNewTxnQueryHere->fetch_assoc() ) { ... }包裹在整个结果区域内,并在其中的不同位置使用echo $row['X'];

2 个答案:

答案 0 :(得分:4)

为什么不使用单个分组查询?

SELECT payment_type, count(*)
FROM transaction
WHERE payment_type IN ('X', 'C', 'K', 'O', 'A')
    AND YEAR(paid_on) = YEAR(curdate())
GROUP BY payment_Type

答案 1 :(得分:1)

您可以使用一个查询

$query = $con->query("SELECT payment_type, COUNT(*) as cnt AS num FROM transaction WHERE YEAR(paid_on) LIKE '%".date ('Y')."%' group by payment_type");
$data = array();
while($row = $query->fetch_assoc()) { 
    $data[$row['payment_type']] = $row['cnt'];
}

所有数据都在数组$data中,例如:echo $data['C'];echo $data['A'];或总数echo array_sum($data);