我有一系列SQL查詢來輸出所有12個月的數值。最小化一系列SQL查詢
$chartIncomejan = $query->fetch("SELECT *, SUM(rent_amount) AS 'num' FROM transaction WHERE paid_on LIKE '%2015-01%'");
$chartIncomefeb = $query->fetch("SELECT *, SUM(rent_amount) AS 'num' FROM transaction WHERE paid_on LIKE '%2015-02%'");
$chartIncomemar = $query->fetch("SELECT *, SUM(rent_amount) AS 'num' FROM transaction WHERE paid_on LIKE '%2015-03%'");
$chartIncomeapr = $query->fetch("SELECT *, SUM(rent_amount) AS 'num' FROM transaction WHERE paid_on LIKE '%2015-04%'");
...
這是我的輸出
if ($chartIncomejan['num'] > '0') { echo $chartIncomejan['num'].','; } else { echo '0,'; }
if ($chartIncomefeb['num'] > '0') { echo $chartIncomefeb['num'].','; } else { echo '0,'; }
if ($chartIncomemar['num'] > '0') { echo $chartIncomemar['num'].','; } else { echo '0,'; }
if ($chartIncomeapr['num'] > '0') { echo $chartIncomeapr['num'].','; } else { echo '0,'; }
...
它作爲回聲逗號分隔值列表碼...等
我想這個代碼減少到最小可能的代碼量,但我不知道從哪裏開始。我應該做陣列嗎?也許是一個foreach語句?如果你可以展示一個例子(不一定用我的代碼),那也會很有幫助。
我不知道爲什麼我會被低估。這是一個真正嘗試學習最佳實踐的人的合理問題... –
什麼數據類型是'paid_on'列 – RiggsFolly
'paid_on'是TIMESTAMP –