我是编程的新手,我有一个错误,我在搜索后无法解决。
我正在使用表单执行搜索并在表格中显示数据,该部分相当容易......但我还想计算最终结果中的天数,而不是我使用的日期对于第一个查询。
查询在两个日期和指定公司之间的天数内搜索结果,问题出在最终结果中,它会计算我的结果中的天数,而不是我搜索的天数。
示例:如果我在2月11日到2月20日之间搜索2个日期公司= 1
如果公司1只有3天的结果,我希望它只计算3天。
我知道我的代码在那部分是错误的,但我无法让它做我想要的。
以下是我的一小段代码来解释它:
if (isset($_POST['search'])) {
$date1 = mysql_prep($_POST['date1']);
$date2 = mysql_prep($_POST['date2']);
$latte = mysql_prep($_POST['latte']);
$query = "SELECT * FROM payroll WHERE (day BETWEEN '{$date1}' AND '{$date2}') AND (company = '{$latte}') ORDER BY day ASC ";
$result = mysql_query($query, $connection);
$woof = "SELECT SUM(hours) FROM (SELECT * FROM payroll WHERE (day BETWEEN '{$date1}' AND '{$date2}') AND (company = '{$latte}') ORDER BY day ASC) AS subt ";
$raw = mysql_query($woof, $connection);
if(!$raw) { die(mysql_error());}
$meow = mysql_result($raw, 0, 0);
$diff = abs(strtotime($date2) - strtotime($date1));
$years = floor($diff / (365*60*60*24));
$months = floor(($diff - $years * 365*60*60*24) / (30*60*60*24));
$days = floor(($diff - $years * 365*60*60*24 - $months*30*60*60*24)/ (60*60*24) +1);
if(!$result) {
echo "FAIL";
} else {
echo "<table>
<tr>
<th> Date </th>
<th> Hours </th>
<th> Job Title </th>
<th> Job Description </th>
<th> Paid </th>
<th> For </th>
</tr>";
while($row = mysql_fetch_array($result))
{
$company = $row['company'];
if($company == 0) {
$company = "Wilson Electric";
} if($company == 1) {
$company = "Wilson Rental";
} if ($company == 2) {
$company = "Church of Christ";
}
echo "<tr>";
echo "<td class=\"center\">" . $row['day'] . "</td>";
echo "<td class=\"center\">" . $row['hours'] . "</td>";
echo "<td style=\"padding:5px;\">" . $row['job_title'] . "</td>";
echo "<td style=\"padding:5px;\">" . $row['job_description'] . "</td>";
echo "<td class=\"center\">" . $row['paid'] . "</td>";
echo "<td style=\"padding:5px;\">" . $company . "</td>";
echo "</tr>";
}
echo "<tr>";
echo "<td class=\"center\"> Total Days: " . $days . "</td>";
echo "<td class=\"center\"> Total Hours: " . $meow . "</td>";
echo "</tr>";
}
}
感谢阅读它,我希望有人可以给我一个解决方案,我知道一定是非常简单的事情,但我无法理解。
答案 0 :(得分:0)
如果要计算与规范匹配的不同day
值,则可以将一个简单表达式添加到“woof”SQL语句的SELECT列表中:
SELECT SUM(hours), COUNT(DISTINCT `day`) AS cnt_days FROM ...
$meow = mysql_result($raw, 0, 0);
$days = mysql_result($raw, 0, 1);
请注意,如果有多个行具有相同的day
值(满足所有谓词),则day
值仅计算一次。如果您希望计数具有非NULL day
值的行(包括任何重复项),则省略DISTINCT关键字。)
请注意,可以更简单地编写SQL语句;你可以省略(不必要的)内联视图(即派生表)和不必要的ORDER BY ...
SELECT SUM(p.hours) AS sum_hours
, COUNT(DISTINCT p.day) AS cnt_days
FROM payroll p
WHERE p.day BETWEEN '{$date1}' AND '{$date2}'
AND p.company = '{$latte}'
答案 1 :(得分:-1)
可以使用DateTime::diff