在DATEDIFF中输入其他计算

时间:2014-07-23 02:51:03

标签: php mysql date

我的客户要求数据库能够计算从date1date2的天数,并且我使用了DATEDIFF,但我是否可以在编码中添加额外的计算?

例如:

(date1-date2)/365*0.1

这个计算可以完成吗?

这是我在output.php

上使用的代码
$result = mysqli_query($con,"SELECT *,DATEDIFF(mdate,pdate)/365*0.1
FROM contacts WHERE DATEDIFF(mdate,pdate)");



    echo 
    "<table border='1'>
    <tr>
    <th>ID</th>
    <th>Difference Date</th>
    <th>Purchased Date</th>
    <th>Maturity Date</th>
    <th>Amount</th>
    <th>First Name</th>
    <th>Last Name</th>
    <th>Passport/ID</th>
    <th>Contact No.</th>
    <th>Mailing Address</th>
    <th>Beneficiary Name</th>
    <th>Swift Code</th>
    <th>Bank Account</th>
    <th>Bank Name</th>
    <th>Bank Address</th>
    <th>Bank Contact No.</th>
    </tr>";

    while($row = mysqli_fetch_array($result)) {
      echo "<tr>";
      echo "<td>" . $row['id'] . "</td>";
      echo "<td>" . $row['DATEDIFF(mdate,pdate)'] . "</td>";
      //echo "<td>" . $row['ddate'] . "</td>";
      echo "<td>" . $row['pdate'] . "</td>";
      echo "<td>" . $row['mdate'] . "</td>";
      echo "<td>" . $row['amt'] . "</td>";
      echo "<td>" . $row['first'] . "</td>";
      echo "<td>" . $row['last'] . "</td>";
      echo "<td>" . $row['pid'] . "</td>";
      echo "<td>" . $row['cno'] . "</td>";
      echo "<td>" . $row['madd'] . "</td>";
      echo "<td>" . $row['bene'] . "</td>";
      echo "<td>" . $row['swc'] . "</td>";
      echo "<td>" . $row['bacc'] . "</td>";
      echo "<td>" . $row['bank'] . "</td>";
      echo "<td>" . $row['badd'] . "</td>";
      echo "<td>" . $row['bno'] . "</td>"; 
      echo "</tr>";
    }

    echo "</table>";

    mysqli_close($con);
    ?>

1 个答案:

答案 0 :(得分:0)

有一个拼写错误:

echo "<td>" . $row['DATEDIFF(mdate,pdate)'] . "</td>";

应该是

echo "<td>" . $row['DATEDIFF(mdate,pdate)/365*0.1'] . "</td>";

要避免这种情况,您可以在查询中对计算字段进行别名,如下所示:

$result = mysqli_query($con,"SELECT *,DATEDIFF(mdate,pdate)/365*0.1 as difference 
                             FROM contacts WHERE DATEDIFF(mdate,pdate)");

并像这样引用它:

echo "<td>" . $row['difference'] . "</td>";