数据库中的日期错误(不可更新)

时间:2017-11-18 17:19:02

标签: php mysql

我有代码:

<!DOCTYPE html>
<html>
<head>
</head>
<body>
<?php
    session_start();
    $conn = mysqli_connect("localhost","root","");
    mysqli_select_db($conn, "test");
?>

<?php
if (isset($_GET['logout'])==1) 
{
    session_destroy();
    $_SESSION['ishere'] = false;
}
?>

<?php
if (isset($_POST['login_button'])) 
{
    $login = $_POST['login'];
    $password = $_POST['password'];

    if (mysqli_num_rows(mysqli_query($conn, "SELECT login, password FROM user WHERE login = '".$login."' AND password = '".$password."';")) > 0) 
    {   
        mysqli_query($conn, "UPDATE user SET 'login_time' = NOW() WHERE login = '".$login."';");

        $_SESSION['ishere'] = true;
        $_SESSION['login'] = $login;        
    }
    else echo "Something went wrong. Try again!";
}

if (isset($_SESSION['ishere'])==true)
{
    echo "Hello <b>".$_SESSION['login']."</b><br><br>";
    $time = mysqli_fetch_all(mysqli_query($conn, "SELECT login_time FROM user WHERE login='".$_SESSION['login']."'"));
    echo "Czas ostatniego logowanie ";
    foreach ($time as $i) {
        echo date('Y-m-d H:i:s', implode($i));
    }
    echo '<a href="?logout=1">[Logout]</a>';
}
?>

<?php if (isset($_SESSION['ishere'])==false): ?>
    <form method="POST" action="login.php">
        <b>Login:</b> <input type="text" name="login"><br>
        <b>Password:</b> <input type="password" name="password"><br>
        <input type="submit" value="Login" name="login_button">
    </form>
<?php endif; ?>

<?php mysqli_close($conn); ?>
</body>
</html> 

字段login_time在我的数据库中作为int,我将其更改为日期。当我登录时,我总是将相同的时间戳转换为日期:1970-01-01 01:00:00。我做错了什么?我认为这个代码在我登录时将更新我的数据库并将login_time设置为当前时间,然后当我再次登录时,将打印新的:(我和我使用的函数如NOW(),time(), date(&#39; Ymd H:i:s&#39;)和CURRENT_TIMESTAMP。如何写入db正确的时间并读取它?

EDIT。我改变了我的代码:

mysqli_query($conn, "UPDATE user SET login_time = now() WHERE login = '".$login."';");

$result = mysqli_query($conn, "SELECT login_time FROM user WHERE login='".$_SESSION['login']."'");
$time = mysqli_fetch_assoc($result);
echo date('Y-m-d H:i:s', $time["login_time"]);

现在我有相同的日期,即使我退出并再次登录。日期是2038年......

EDIT2。 UNIX_TIMESTAMP()是一个解决方案:)

1 个答案:

答案 0 :(得分:1)

不要在列名称周围使用引号(当需要时最终使用backtics)引用是字面值

"UPDATE user SET login_time = NOW() WHERE login = '".$login."';");