MySQL PHP – How to Add DATETIME Value for Session User

datetimeMySQLPHP

I am maintaining two tables:

  • Employee table consists of username and password(for logging in)
  • log table consists of login and logout time for the session user

With the click of a button, I should be able to capture/insert the time and session user to log table.

Here is my code for logging time and session user:

 <?php

session_start();
     if($_SESSION['username']) {
        $user = $_SESSION['username'];
    $tin= $_POST["timein"];
            $conn = mysql_connect("localhost","root","");

            mysql_select_db("attendance", $conn);

            $query = "INSERT INTO log (user, timein) VALUES ($user , NOW())";

            mysql_query($query, $conn);

            echo "<h2>you have logged your time!</h2>";

            mysql_close($conn);
    }
?>

Best Answer

I see two problems with

$query = "INSERT INTO log (user, timein) VALUES ($user , NOW())";

Problem #1 : You need quotes around $user

Problem #2 : You need use timein instead of NOW()

Now, you need to make a decision.

If you want to supply the time yourself, then the query should be

$query = "INSERT INTO log (user, timein) VALUES ('$user','$tin')";

If you want the DB Server's clock time, then the query should be

$query = "INSERT INTO log (user, timein) VALUES ('$user',NOW())";

thus eliminating the need for $tin= $_POST["timein"];