I am developing a tool to log come-and-go - times of workers. These times are logged into a single mysql-table.
The table has a come
and a gone
field to register when a worker is coming or leaving.
New entries should only be made, if all "old" entries are closed, means the worker has checked-out before.
I am thinking it should look like:
IF EXISTS ( SELECT * FROM tbl_card
WHERE time_gone IS NULL
AND user_id=".$user_id."
)
THEN
BEGIN
END
ELSE BEGIN
INSERT
INTO tbl_card (`user_id`, `time_come`)
VALUES ('2', '2018-01-01 14:00')
END
Does anyone have an idea how this should work?
I am using php to query mysql. Php allowed to define "if-conditions", so I seperated the queries in SELECT * FROM tbl_card...
and tested if the rowcount
is '0' and then I executed the insert.
BUT: One user managed to use the microseconds between first and second query to check-in twice. :(
It is used in a LAMP-environment. Before it was like:
$sql = "SELECT * FROM tbl_card WHERE time_gone IS NULL
AND user_id=".$user_id;
$result = $db_conn->query($sql);
if ($result->num_rows <> 0)
{
return 'You already checked in!';
}
else
{
$sql = "INSERT
INTO tbl_card(`user_id`, `time_come`)
VALUES ('".$user_id."', '".$timestamp."')";
if ($db_conn->query($sql)){
return 'Check in: '.$timestamp;}
else
{
return 'Something strange happend!';
}
}
Tables are:
tbl_card -> id, user_id, time_come, time_gone
tbl_user -> id, name