我正在尝试创建一个图表,该图表从我们的某个数据库获取数据,并计算过去12个月中每个问题的数量。查询运行正常,但即使数据库中存在与查询匹配的记录,它仍会返回0结果。我使用的代码如下......
<?php
if (isset($_POST['dept'])) {
$dept = $_POST['dept'];
} else {
$dept = '';
}
for ($i = 1; $i <= 12; $i++) {
$months[] = date("Y-m-d", strtotime(date('Y-m-01') . " -$i months"));
}
foreach ($months as $month => $value) {
$theMonth = date("M", strtotime($value));
$theYear = date("Y", strtotime($value));
$sql = "SELECT `c_ID`, `department`, `departmentSub`, `todaysDate`, \n" . "SUM(CASE WHEN department='$dept' AND departmentSub LIKE 'Loading Error' AND MONTH(todaysDate) = MONTH($value) AND YEAR(todaysDate) = YEAR($value) THEN 1 ELSE 0 END) AS loadingErrors,\n" . "SUM(CASE WHEN department='$dept' AND departmentSub LIKE 'Bad Customer Service' AND MONTH(todaysDate) = MONTH($value) AND YEAR(todaysDate) = YEAR($value) THEN 1 ELSE 0 END) AS custService\n" . "FROM `nonConformance`";
if ($result = mysqli_query($conn, $sql)) {
// Return the number of rows in result set
while ($row = $result->fetch_assoc()) {
$loadingErrors = $row['loadingErrors'];
$custService = $row['custService'];
}
}
}
?>
我无法弄清楚为什么这不会返回任何结果,任何人都可以帮助我,我会非常感激。
谢谢!
[示例数据] http://imgur.com/g0UzcpR
答案 0 :(得分:1)
在您的查询中,您不会将$value
作为字符串传递。尝试使用撇号围绕$value
:
$sql = "SELECT `c_ID`, `department`, `departmentSub`, `todaysDate`, \n" . "SUM(CASE WHEN department='$dept' AND departmentSub LIKE 'Loading Error' AND MONTH(todaysDate) = MONTH('$value') AND YEAR(todaysDate) = YEAR('$value') THEN 1 ELSE 0 END) AS loadingErrors,\n" . "SUM(CASE WHEN department='$dept' AND departmentSub LIKE 'Bad Customer Service' AND MONTH(todaysDate) = MONTH('$value') AND YEAR(todaysDate) = YEAR('$value') THEN 1 ELSE 0 END) AS custService\n" . "FROM `nonConformance`";
MONTH($value)
变为MONTH('$value')
,YEAR($value)
变为YEAR('$value')
另外,请确保您在$loadingErrors
循环中输出$custService
和foreach ($months as $month => $value) {
的值,否则具有零值的日期将覆盖之前的值。
答案 1 :(得分:0)
您是否在查询中尝试了此操作?
替换
departmentSub LIKE 'Loading Error'
与
departmentSub = 'Loading Error'
或
departmentSub LIKE '%Loading Error%'
如果您要查找精确的字符串值,为什么要使用LIKE?