首页 > 解决方案 > 如果无效,则将 id 相互匹配,如果不显示错误,则显示数据正确。显示正确和不正确的错误

问题描述

目录:

  1. 快速运行代码的作用。
  2. 代码
  3. 成功。
  4. 错误
  5. 我所期望的和实际输出的
  6. 我试图解决这些错误的方法

1. 快速了解代码的作用。

它是一个简单的时钟进出系统,使用 RFID 阅读器。用户有一个字段,在员工刷卡后使用阅读器本身归档。我使用 ajax 脚本来处理发布,一旦提交表单,PHP 会处理其余部分。

我创建了一个简单的系统。检查当前日期和表格日期是否匹配,如果员工当天还没有打卡。插入时间戳并为下一位员工重新加载页面。

2. 代码

HTML 和 JS

       $("body").on("submit", "#clockInOut", function(e){
            var rfidNumber = $('#rfidNumber').val();
            swal.showLoading();
            if (rfidNumber == "") {
                swal.fire({
                    icon: "error",
                    title: "No Input",
                    html: "<b>Enter Your Employee ID, cannot be blank!</b>",
                    timer: 1500,
                    showConfirmButton: false
                });
            } else {
                e.preventDefault();
                $.ajax({
                    type: "POST",
                    url: "<?= $site->baseURL; ?>/",
                    dataType: "json",
                    data: {
                        rfidNumber: rfidNumber
                    },
                    success: function ( result ) {
                        $('#rfidNumber').val('');
                        console.log(result);
                        if (result.success) {
                            swal.fire({
                                icon: "success",
                                title: result.title ,
                                html: result.html,
                                showConfirmButton: false,
                                timer: 2000 
                            });
                        } else if (result.error) {
                        swal.fire({
                            icon: "error",
                            title: result.title,
                            html: result.html,
                            showConfirmButton: false,
                            timer: 5000
                        });
                        }
                    },
                    error: function ( result ) {
                        console.log(result);
                    }
                });
            }
       });
    <div class="login-box" style="height: 100%; margin-top: 5%;">
        <div class="login-logo">
            <a>
                <?= "<img src='" . $site->info['logo'] . "' style='height: 100px; width: 100px;'><br /><b>" . $site->info['title'] . "</b>" ?></a>
        </div>
        <!-- /.login-logo -->
        <div class="card">
            <div class="card-body login-card-body">
                <p class="login-box-msg">
                    <div class="login-logo">
                        <p id="date"></p>
                        <p id="time" class="bold"></p>
                    </div>
                </p>
                <form id="clockInOut" method="post">

                    <div class="input-group mb-3">
                        <input type="text" class="form-control" minlength="7" maxlength="8" oninput="this.value = this.value.replace(/[^1-9.]/g, '').replace(/(\..*)\./g, '$1');" id="rfidNumber" placeholder="RFID Number" required autofocus>
                        <div class="input-group-append">
                            <div class="input-group-text">
                                <span class="fa fa-user"></span>
                            </div>
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-4">
                        </div>
                        <div class="col-4 text-center">
                            <button type="submit" class="btn btn-block btn-outline-primary">Submit</button>
                        </div>
                        <!-- /.col -->
                    </div>
                </form>
                <hr>
                <p class="mb-1">
                    <a href="forgot-password.html">I forgot my Employee ID</a>
                </p>
            </div>
            <!-- /.login-card-body -->
        </div>
        <center>
        </center>
    </div>

PHP 处理程序

if(isset($_POST['rfidNumber'])){

    $rfidNumber = $_POST['rfidNumber'];

  $getRfidNumbers = $functions->runSQL("SELECT `id`, `employee_id`, `rfid_card_number` FROM `employeeids` WHERE `available` = '0'");
  $getRfidNumbers->execute();

  $rfidNumbers = $getRfidNumbers->fetchAll(PDO::FETCH_ASSOC);
  $rfidArr = [];
  foreach ($rfidNumbers as $key => $value) {
    $rfidArr = array($value['rfid_card_number']);
  }
  // Check If Employee ID exists
  if (!in_array($rfidNumber, $rfidArr)) {
      $error = array(
        "error" => "error",
        "title" => "<b style='color:red;'>Invalid RFID Number</b>",
        "html" => "<b>Forgot Your RFID Number ?<br />Use the Forgot link to get your RFID Number.</b>"
      );
      print json_encode($error); 
  }

  $currentTime = date("H:i:s");
  $date = date('Y-m-d');

  foreach ($rfidNumbers as $key => $value) {
     if ($rfidNumber == $value['rfid_card_number']) {
      $getAttendance = $functions->runSQL("SELECT `id`, `employee_id`, `rfid_card_number`, `date`, `clock_in`, `status`, `clock_out`, `num_hours` FROM `attendance` WHERE `rfid_card_number` = :rfidNumber");
      $getAttendance->execute(array(
        ":rfidNumber" => $value['id']
      ));
      $attendance = $getAttendance->fetchAll(PDO::FETCH_ASSOC);

      $getEmployeeDetails = $functions->runSQL("SELECT `firstname`, `lastname` FROM `employees` WHERE `rfid_card_number` = :rfidNumber");
      $getEmployeeDetails->execute(array(
        ":rfidNumber" => $value['id']
      ));
      $employeeDetails = $getEmployeeDetails->fetch(PDO::FETCH_ASSOC);
      $employeeName = $employeeDetails['firstname'] . " " . $employeeDetails['lastname'];

      if ($attendance == NULL) {
        // Not Clocked In
        $workingHoursStart = explode(':', $dashboard->workingHours['open']);
        $clockInGrace = $workingHoursStart[1] + $dashboard->attendanceGrace['in'];
        $ontime = $workingHoursStart[0] . $clockInGrace . $workingHoursStart[2];
        if (date("Y-m-d H:i:s") > date("Y-m-d " . $ontime)) {
          // Employee Late
          $insertClockInLate = $functions->runSQL("INSERT INTO `attendance`(`employee_id`, `rfid_card_number`, `date`, `clock_in`, `status`, `clock_out`, `num_hours`) VALUES (:employeeID, :rfidNumber, :dates, :clockIn, 'late', NULL, '0')");
          $insertClockInLate->bindparam(":employeeID", $value['employee_id']);
          $insertClockInLate->bindparam(":rfidNumber", $value['id']);
          $insertClockInLate->bindparam(":dates", $date);
          $insertClockInLate->bindparam(":clockIn", $currentTime);
          if ($insertClockInLate->execute()) {
            $clockedIn = array(
              "success" => "success",
              "title" => "<b>" . $employeeName . "<b style='color:red;'>(LATE)</b></b>",
              "html" => "<center style='font-size:22px;><b style='color:green;'>Clocked In</b><b style='color:red;'> Your&apos;e late.</b></center>'"
            );
            print json_encode($clockedIn);
          }
        } elseif (date('Y-m-d H:i:s') < date("Y-m-d " . $workingHoursStart[1])) {
          // Employee Early
          $insertClockInEarly = $functions->runSQL("INSERT INTO `attendance`(`employee_id`, `rfid_card_number`, `date`, `clock_in`, `status`, `clock_out`, `num_hours`) VALUES (:employeeID, :rfidNumber, :dates, :clockIn, 'early', NULL, '0')");
          $insertClockInEarly->bindparam(":employeeID", $value['employee_id']);
          $insertClockInEarly->bindparam(":rfidNumber", $value['id']);
          $insertClockInEarly->bindparam(":dates", $date);
          $insertClockInEarly->bindparam(":clockIn", $currentTime);
          if ($insertClockInEarly->execute()) {
            $clockedIn = array(
              "success" => "success",
              "title" => "<b>" . $employeeName . "<b style='color:green;'>(Early)</b></b>",
              "html" => "<center style='font-size:22px;><b style='color:green;'>Clocked In</b><b style='color:green;'> Your&apos;e Early.</b></center>"
            );
            print json_encode($clockedIn);
          }
        } elseif (date("Y-m-d H:i:s") < date("Y-m-d " . $ontime)) {
          // Employee On Time
          $insertClockInOnTime = $functions->runSQL("INSERT INTO `attendance`(`employee_id`, `rfid_card_number`, `date`, `clock_in`, `status`, `clock_out`, `num_hours`) VALUES (:employeeID, :rfidNumber, :dates, :clockIn, 'on-time', NULL, '0')");
          $insertClockInOnTime->bindparam(":employeeID", $value['employee_id']);
          $insertClockInOnTime->bindparam(":rfidNumber", $value['id']);
          $insertClockInOnTime->bindparam(":dates", $date);
          $insertClockInOnTime->bindparam(":clockIn", $currentTime);
          if ($insertClockInOnTime->execute()) {
            $clockedIn = array(
              "success" => "success",
              "title" => "<b>" . $employeeName . "<b style='color:green;'>(ON-TIME)</b></b>",
              "html" => "<center style='font-size:22px;><b style='color:green;'>Clocked In</b><b style='color:green;'> Your&apos;e On-Time.</b></center>'"
            );
            print json_encode($clockedIn);
          }
        }
      } else {
        // Employee Clock Out
        foreach ($attendance as $key => $ta_attendance) {
          if ( $ta_attendance['date'] == $date ) {
            print json_encode($ta_attendance);
          }
        }
      }
    }
  }
}

3. 成功

我能够将员工 ID 相互匹配,如果有效,则将用户出勤输入数据库,同时检查是否早、准、晚。如果无效显示错误。

4. 错误

DB 出勤率为 0。如果我在一个用户中使用并打卡,那就成功了

html: "<center style='font-size:22px;>Clocked In Your'e late.'" success: "success" title: " Lola1 Sec1(LATE) "

第二个时钟,即使用户是有效的:

responseText: "{"error":"error","title":"Invalid RFID Number<\/b>","html":" Forgot Your RFID Number ?<br \/>使用忘记链接获取您的 RFID Number.<\/b>"}{"success":"success","title":" Lola Sec(LATE)<\/b><\/b>","html":"<center style=' font-size:22px;>Clocked In<\/b>你迟到了。<\/b><\/center>'"}"

如果用户输入无效的 id,则会显示正确的错误

错误:“错误” html:“忘记了您的 RFID 号码?
使用忘记链接获取您的 RFID 号码。
”标题:“无效的 RFID 号码

如果用户打卡(第一个没有错误)试图打卡,响应是:

responseText: "{"error":"error","title":"无效的 RFID 号码<\/b>","html":"忘记了您的 RFID 号码?<br \/>使用忘记链接获取您的 RFID号码。<\/b>"}{"id":"130","employee_id":"FSJ0001","rfid_card_number":"1","date":"2020-12-31","clock_in": "21:10:48","status":"late","clock_out":null,"num_hours":"0"}"

仍然显示无效错误。

现在,当用户再次尝试使用有效 id 打卡时。无效键显示

responseText: "{"error":"error","title":"无效的 RFID 号码<\/b>","html":"忘记了您的 RFID 号码?<br \/>使用忘记链接获取您的 RFID号码。<\/b>"}{"id":"130","employee_id":"FSJ0001","rfid_card_number":"1","date":"2020-12-31","clock_in": "21:10:48","status":"late","clock_out":null,"num_hours":"0"}"

5. 我尝试解决这些错误的方法

  if (!in_array($rfidNumber, $rfidArr)) {
      $error = array(
        "error" => "error",
        "title" => "<b style='color:red;'>Invalid RFID Number</b>",
        "html" => "<b>Forgot Your RFID Number ?<br />Use the Forgot link to get your RFID Number.</b>"
      );
      print json_encode($error); 
  }

我在 if 语句的开头移动了上面的脚本,做同样的事情。

如果我删除它并添加一个elseif ($value['rfid_card_number'] !== $rfidNumber)仍然会做同样的事情,但会有一些不同的错误。

**注意:EmployeeIds 表存储实际的 rfid 编号,其余 dbs 存储 id **

我已经使用了 2 天,似乎无法找到解决此错误的方法,或者是否有办法。

标签: javascriptphpjqueryajax

解决方案


是时候重构了!

当您看不到所有树木的森林时,就该重构了。当我查看您的代码时,我一直迷失在第二个foreach ($rfidNumbers as $key => $value)循环中的所有内容中。具有讽刺意味的是,它甚至没有到达第二个用户那里。

初始问题的调试步骤:

所有错误都归结为一件事:您没有在employeeids. 这就提出了一个问题:为什么要下载整个表然后搜索整个数组,而您可以在数据库查询中这样做呢?

"SELECT id, employee_id, rfid_card_number FROM employeeids WHERE available = '0' and rfid_card_number=:rfidNumber"

在 phpmyadmin 中运行该查询,并检查(缺少)结果。然后运行 ​​aselect * from employeeids并查看查询失败的原因。您没有显示任何影响该字段的代码available,但我怀疑它可能有一个空值,这将导致查询忽略该行。或者,也许您正在将状态更改为available非零值。

提示:它甚至可能没有在你认为失败的记录上失败。对于调试,您可以在错误中添加 rfid 编号/员工 ID。您还应该exit在任何print json_encode($error);.

进一步的问题

  foreach ($rfidNumbers as $key => $value) {
     if ($rfidNumber == $value['rfid_card_number']) {

如果您只从employeeids 中获取所需的记录,则循环是不必要的。


$getAttendance = $functions->runSQL("SELECT `id`, `employee_id`, `rfid_card_number`, `date`, `clock_in`, `status`, `clock_out`, `num_hours` FROM `attendance` WHERE `rfid_card_number` = :rfidNumber");

此查询将收集所有登录记录,而不是当前记录。你可能想要order by id desc limit 1


if ($attendance == NULL) {

需要检查字段,而不是行。这只会在您第一次运行脚本时进行。


您应该在这里重构所有重复的代码:

        if (date("Y-m-d H:i:s") > date("Y-m-d " . $ontime)) {
          // Employee Late
          $insertClockInLate = $functions->runSQL("INSERT INTO `attendance`(`employee_id`, `rfid_card_number`, `date`, `clock_in`, `status`, `clock_out`, `num_hours`) VALUES (:employeeID, :rfidNumber, :dates, :clockIn, 'late', NULL, '0')");
          $insertClockInLate->bindparam(":employeeID", $value['employee_id']);
          $insertClockInLate->bindparam(":rfidNumber", $value['id']);
          $insertClockInLate->bindparam(":dates", $date);
          $insertClockInLate->bindparam(":clockIn", $currentTime);
          if ($insertClockInLate->execute()) {
            $clockedIn = array(
              "success" => "success",
              "title" => "<b>" . $employeeName . "<b style='color:red;'>(LATE)</b></b>",
              "html" => "<center style='font-size:22px;><b style='color:green;'>Clocked In</b><b style='color:red;'> Your&apos;e late.</b></center>'"
            );
            print json_encode($clockedIn);
          }
        } elseif (date('Y-m-d H:i:s') < date("Y-m-d " . $workingHoursStart[1])) {
          // Employee Early
          $insertClockInEarly = $functions->runSQL("INSERT INTO `attendance`(`employee_id`, `rfid_card_number`, `date`, `clock_in`, `status`, `clock_out`, `num_hours`) VALUES (:employeeID, :rfidNumber, :dates, :clockIn, 'early', NULL, '0')");
          $insertClockInEarly->bindparam(":employeeID", $value['employee_id']);
          $insertClockInEarly->bindparam(":rfidNumber", $value['id']);
          $insertClockInEarly->bindparam(":dates", $date);
          $insertClockInEarly->bindparam(":clockIn", $currentTime);
          if ($insertClockInEarly->execute()) {
 ...etc

类似于

$workingHoursStart = explode(':', $dashboard->workingHours['open']);
$clockInGrace = $workingHoursStart[1] + $dashboard->attendanceGrace['in'];
$ontime = $workingHoursStart[0] . $clockInGrace . $workingHoursStart[2];
$now = date('Y-m-d H:i:s');

$clock_out = null;
if($now > date('Y-m-d').' '.$ontime) {
    $status = 'late';
    $message = [
        "success" => "success",
        "title" => "<b>" . $employeeName . "<b style='color:red;'>(LATE)</b></b>",
        "html" => "<center style='font-size:22px;><b style='color:green;'>Clocked In</b><b style='color:red;'> Your&apos;e late.</b></center>'"
    ];
}
if($now < $date('Y-m-d') . ' ' . $workingHoursStart[1]) {
    $status = 'early';
    $message = [
        "success" => "success",
        "title" => "<b>" . $employeeName . "<b style='color:green;'>(Early)</b></b>",
        "html" => "<center style='font-size:22px;><b style='color:green;'>Clocked In</b><b style='color:green;'> Your&apos;e Early.</b></center>"
    ];
if (date("Y-m-d H:i:s") < date("Y-m-d " . $ontime)) {
    $status = 'on-time';
    $message = [
        "success" => "success",
        "title" => "<b>" . $employeeName . "<b style='color:green;'>(ON-TIME)</b></b>"
        "html" => "<center style='font-size:22px;><b style='color:green;'>Clocked In</b><b style='color:green;'> Your&apos;e On-Time.</b></center>'"
    ];
}

$insertClockInOnTime = $functions->runSQL("INSERT INTO `attendance`(`employee_id`, `rfid_card_number`, `date`, `clock_in`, `status`, `clock_out`, `num_hours`) VALUES (:employeeID, :rfidNumber, :dates, :clockIn, :status, NULL, '0')");
$insertClockInOnTime->bindparam(":employeeID", $value['employee_id']);
$insertClockInOnTime->bindparam(":rfidNumber", $value['id']);
$insertClockInOnTime->bindparam(":dates", $date);
$insertClockInOnTime->bindparam(":clockIn", $currentTime);
$insertClockInOnTime->bindparam(":status", $status);

我没有重构$message,但它也可以很容易地重构,特别是如果您使用 css 而不是内联样式。


推荐阅读