2012-03-28 90 views
1

什么是正确的方式来使用MySQL TIMEDIFF,(或类似的)?在数据库中我有一个名为date的列,它设置CURRENT_TIMESTAMP。我试图计算连续CURRENT_TIMESTAMP和现在之间的differene,比呼应,为所有的行..这是我的脚本sql timediff函数

<?php 
    mysql_connect("localhost","root","");//database connection 
    mysql_select_db("beyondmotors"); 

    $result = mysql_query("SELECT * FROM currentrentals"); 

    echo "<table border='2'> 
    <tr> 
    <th>ID</th> 
    <th>Year</th> 
    <th>Make</th> 
    <th>Model</th> 
    <th>First Name</th> 
    <th>Last Name</th> 
    <th>Insurance</th> 
    <th>Date</th> 
    <th>Notes</th> 
    </tr>"; 

    while($row = mysql_fetch_array($result)) 
    { 
    echo "<tr>"; 
    echo "<td>" . $row['id'] . "</td>"; 
    echo "<td>" . $row['year'] . "</td>"; 
    echo "<td>" . $row['make'] . "</td>"; 
    echo "<td>" . $row['model'] . "</td>"; 
    echo "<td>" . $row['firstname'] . "</td>"; 
    echo "<td>" . $row['lastname'] . "</td>"; 
    echo "<td>" . $row['insurance'] . "</td>"; 
    echo "<td>" . $row['date'] . "</td>"; 
    echo "<td>" . $row['notes'] . "</td>"; 
     echo ("<td><a href=\"edit_form.php?id=$row[id]\">Edit</a></td></tr>"); 
     echo "</tr>"; 
     } 
    echo "</table>"; 

在此先感谢

回答

3

这可能严重依赖于您的输出。

例如,TIMEDIFF()输出是小时,分钟,秒。因此,它仅限于数据类型TIME

给定一个单位SECOND,TIMESTAMPDIFF()是一个更强大的解决方案。

所有这些在MySQL Date and Time functions中都有详细记录。

最后,您通常会看到使用代码完成的这些计算。这不是用SQL。在你的情况下PHP。您可以通过从strtotime()减去时间戳来进行简单的算术运算。或者,如果您使用PHP> = 5.3,则可以使用DateTime::diff

另外,请避免命名您的列关键字,即date

0

我会做这样的:

SELECT (fields), UNIX_TIMESTAMP(date) as date FROM currentrentals 

然后你可以访问日期$row['date']。现在您可以轻松减去这些日期。

$timesince = date(format, time() - $row['date']); 

希望有帮助。