elseif mysql查询未返回任何行时

时间:2019-01-24 17:13:12

标签: php mysql mysqli

我正在制作一个简单的时钟系统,使员工可以记录他们的工作时间。

我有一个表,用于存储时间戳和天气情况,这是一个上班或下班的操作。根据给定用户的最后操作,显示相反的选项。例如,如果最后一个动作是时钟退出,则所显示的动作应该是时钟进入。

在用户未使用系统的情况下,应向他们提供登录选项。

$sql_status = "SELECT * FROM timeclock WHERE employeeid = $employee_number ORDER BY id DESC LIMIT 1";
if ($result=$mysqli->query($sql_status)) {
    while ($row = $result->fetch_row()){
        $timeclock_action = $row[2];
        $timeclock_timestamp = $row[3];
            if($timeclock_action=="out") {
                $forward_action = "clockin";
                $forward_action_label = "Clock in";
                $timeclock_status_label = "Last clock out: ";
            } elseif($timeclock_action=="in") {
                $forward_action = "clockout";
                $forward_action_label = "Clock out";
                $timeclock_status_label = "Clocked in: ";
            }
    }
} elseif(mysql_num_rows($result)==0) {
    $forward_action = "clockin";
    $forward_action_label = "Clock in";
    $timeclock_status_label = "You've never clocked in before";
} else {
    echo "Error: " . $sql . "<br>" . $mysqli->error;
}

我的想法是,如果mysql查询返回0行,则将相应地设置变量,但根本不会设置它们。 我在哪里想错了?谢谢!

1 个答案:

答案 0 :(得分:3)

您当前的逻辑是,如果查询失败-即查询返回 false 的时间(不是它没有返回任何结果,而是完全执行了失败),则检查返回的行数是否为零。

相反,您应该首先执行查询,然后检查是否返回任何行。您也不需要循环多行,因为您只希望查询中带有LIMIT 1的一行。

您还应该考虑使用准备好的语句,而不是直接在查询中注入变量,并进行其他一些错误处理;因为永远不要将错误直接显示给用户(记录错误,并显示通用的“出了点问题”消息)。

// The query to be executed
$sql_status = "SELECT * FROM timeclock WHERE employeeid = $employee_number ORDER BY id DESC LIMIT 1";

// See if the query was successful or not
if ($result = $mysqli->query($sql_status)) {
    // If there are any rows returned
    if ($result->num_rows) {
        // Fetch rows - no need for a loop since you only expect one record (LIMIT 1 in the query)
        $row = $result->fetch_row();
        $timeclock_action = $row[2];
        $timeclock_timestamp = $row[3];

        if ($timeclock_action=="out") {
            $forward_action = "clockin";
            $forward_action_label = "Clock in";
            $timeclock_status_label = "Last clock out: ";
        } elseif ($timeclock_action=="in") {
            $forward_action = "clockout";
            $forward_action_label = "Clock out";
            $timeclock_status_label = "Clocked in: ";
        }
    } else {
        $forward_action = "clockin";
        $forward_action_label = "Clock in";
        $timeclock_status_label = "You've never clocked in before";
    }
} else {
    // The query failed
    echo "Error: " . $sql . "<br>" . $mysqli->error;
}