繁体   English   中英

SQL选择/插入/更新查询PHP MySQL

[英]SQL Select/ Insert / Update query PHP MySQL

我有一个带有列userID(int),timeIN(date),timeOUT(date)的表

我在mysql数据库中插入一条记录。 首先,我从另一个表中检查userID是否正确,如果正确,它将添加新的userID和timeIN(date)记录,而timeOUT将为NULL,否则,如果userID不正确,它将显示错误。 我希望我的代码能够检查用户当前是否为timeIN,这样可以防止重复输入。 如果userID的值等于用户输入并且timeIN不为null并且timeOUT为null,我也想插入或更新timeOUT(date)。

请帮助...谢谢。

这是我用于插入userID和timeIN的代码:插入mysql数据库时,它起作用。

<?php
if($_SERVER['REQUEST_METHOD']=='POST'){
require_once('dbConnect.php');

$userID = $_POST['userID'];
$sql = "SELECT * FROM employee WHERE userID='$userID'";
$result = mysqli_query($con,$sql);
$check = mysqli_fetch_array($result);

if(isset($check)){
    $sql = "INSERT INTO dtr (userID,timeIN) VALUES ('$userID', now())";
    mysqli_query($con, $sql);
    echo 'Time IN Successful!';
    }else{
        echo 'Invalid USER ID. Please try again!';
        }           
 mysqli_close($con);
}
?>

您应该在数据库内部处理这些检查。 您正在数据库中执行的当前检查可以通过外键约束来处理:

alter table dtr add constraint fk_dtr_userId
    foreign key (userId) references employee(userId);

第二个意味着您只需要一个具有NULl值的行。 理想情况下,可以使用唯一约束来处理:

alter table dtr add constraint unq_dtr_userId_timeOut
    unique (userId, timeOut);

不幸的是(对于这种情况),MySQL允许重复的NULL值用于唯一约束。 因此,您可以执行以下两项操作之一:

  • 使用默认值,例如“ 2099-12-31”来超时。
  • 使用触发器来强制唯一性

无论哪种情况, 数据库本身都将验证数据,因此无论数据如何插入或更新,您都可以确信数据的完整性。

我是通过未经测试的手机完成的,但您会了解发生了什么

if(isset($check))
{

$sql="SELECT * FROM dtr WHERE userID = $userID";
$result = mysqli_query($con,$sql);
$check = mysqli_fetch_array($result);

if(isset($check))
{
    echo "Already in";
    if(isset($check['timeIN']) && !isset($check['timeOUT']))
    {
        $sql = "UPDATE dtr SET timeOUT= now() WHERE userID=$userID";
        mysqli_query($con, $sql);
        mysqli_close($con);
    }
}
else
{
    $sql = "INSERT INTO dtr (userID,timeIN) VALUES ('$userID', now())";
    mysqli_query($con, $sql);
    mysqli_close($con);
    echo 'Time IN Successful!';
}
}
else
{
echo 'Invalid USER ID. Please try again!';
mysqli_close($con);
}           

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM