简体   繁体   中英

php comparing dates

i have table with two fields

competition {stateTime, endTime}

when i insert to that table i want to ensure that the value i want to insert it is not on the period of any row in that table i type this function (PDO Database)

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;
    }

but doesn't work good, every date in database is yyyy-mm-dd , example 2012-01-15

May i suggest that rather then writing a function that tests existence and returns a bool that you return the records, this way you can later test whether none were returned but if there was you can the use them if needed. As Alvin Wong suggests you can use BETWEEN in your sql so you get something like this.

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();
}

and later/somewhere else

$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);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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