使用MySQLI将DateDiff列添加到PHP表

时间:2015-11-06 19:08:53

标签: php mysql mysqli datediff

我试图在我的数据库表中添加一列,显示时间戳和当前日期之间的差异。我尝试使用DateDiff创建另一个查询,但我不确定我做错了什么。 有人可以帮忙吗?

我的代码如下。

    <?php
            $result = mysqli_query($con,"SELECT * FROM pokemon ORDER BY stats");

            echo "<table border='1'>
            <tr>
            <th>Pokemon Name</th>
            <th>Type One</th>
            <th>Type Two</th>
            <th>Move One</th>
            <th>Move Two</th>
            <th>Move Three</th>
            <th>Move Four</th>
            <th>Stats</th>
            <th>ID</th>
            <th>Date Added</th>
            <th>Days on File</th>
            </tr>";

            while($row = mysqli_fetch_array($result))
            {
                $query = "SELECT DATEDIFF(CURDATE, $row[dAdded])FROM pokemon AS days";
                $date =  mysqli_query($con, $query);


            echo "<tr>";
            echo "<td>" . $row['pName'] . "</td>";
            echo "<td>" . $row['type1'] . "</td>";
            echo "<td>" . $row['type2'] . "</td>";
            echo "<td>" . $row['move1'] . "</td>";
            echo "<td>" . $row['move2'] . "</td>";
            echo "<td>" . $row['move3'] . "</td>";
            echo "<td>" . $row['move4'] . "</td>";
            echo "<td>" . $row['stats'] . "</td>";
            echo "<td>" . $row['ID'] . "</td>";
            echo "<td>" . $row['dAdded'] . "</td>";
            echo "<td>" . $date . "days</td>";
            echo "</tr>";
            }
            echo "</table>";
        ?>

2 个答案:

答案 0 :(得分:1)

您可以将datediff添加到原始查询中。您还需要使用fetch_assoc而不是fetch_array,以便您可以在$ row中引用字段名称。

$result = mysqli_query($con,"SELECT *, DATEDIFF(CURDATE, dAdded) as dDate FROM pokemon ORDER BY stats");
while($row = mysqli_fetch_assoc($result))
{

}

答案 1 :(得分:0)

我怀疑问题出在您的DATEDIFF()函数中,更具体地说是$row[dAdded]。这不应该是$row['dAdded']的引号吗?而且我相信CURDATE需要括号CURDATE()

DATEDIFF(CURDATE(), $row['dAdded'])