0

我有两个字段的表

competition {stateTime, endTime}

当我插入该表时,我想确保我要插入的值不在该表中任何行的周期内,我键入此函数(PDO 数据库)

function isCompetitionInAnotherCompetition($startTime, $endTime) {
        $query = "SELECT * FROM competition";
        $sth = $this->db->prepare($query);
        $sth->execute(array());
        while ($row = $sth->fetch()) {
            if ($startTime >= $row['startTime'] && $startTime <= $row['endTime'])
                return true;
            if ($endTime >= $row['startTime'] && $endTime <= $row['endTime'])
                return true;
        }
        return false;
    }

但效果不好,数据库中的每个日期都是yyyy-mm-dd,例如2012-01-15

4

1 回答 1

1

我可以建议不要编写一个函数来测试存在并返回一个返回记录的布尔值,这样你以后可以测试是否没有返回记录,但如果有的话,你可以在需要时使用它们。正如 Alvin Wong 建议的那样,你可以BETWEEN在你的 sql 中使用,所以你会得到这样的东西。

function getCompetitionsBetween($startTime, $endTime) {     

    $startTime = date("Y-m-d", $startTime);
    $endTome = date("Y-m-d", $startTime);

    $query = "SELECT * FROM competition 
               WHERE start_time BETWEEN ? AND ? 
               OR end_time BETWEEN ? AND ?";

    $sth = $this->db->prepare( $query );

    $sth->execute( array($startTime, $endTime, $startTime, $endTime) );

    return $sth->fetchAll();
}

后来/其他地方

$competitions = getCompetitionsBetween($startTime, $endTime);

if (empty(competitions)) {
    $this->save();
} else {
    echo ('sorry the following competitions conflict with these dates');
    foreach($competitions as $k => $v) {
        echo ($k . ':' . $v);
    }
}
于 2012-07-01T15:15:35.153 回答