Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/254.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
php比较日期_Php_Mysql_Pdo - Fatal编程技术网

php比较日期

php比较日期,php,mysql,pdo,Php,Mysql,Pdo,我有两个字段的表 competition {stateTime, endTime} 当我插入到该表中时,我希望确保我要插入的值不在该表中任何行的周期上 我键入此函数(PDO数据库) 函数是竞争性的另一个竞争($startTime,$endTime){ $query=“从竞争中选择*”; $sth=$this->db->prepare($query); $sth->execute(array()); 而($row=$sth->fetch()){ 如果($startTime>=$row['star

我有两个字段的表

competition {stateTime, endTime}
当我插入到该表中时,我希望确保我要插入的值不在该表中任何行的周期上 我键入此函数(PDO数据库)

函数是竞争性的另一个竞争($startTime,$endTime){
$query=“从竞争中选择*”;
$sth=$this->db->prepare($query);
$sth->execute(array());
而($row=$sth->fetch()){

如果($startTime>=$row['startTime']&&$startTime=$row['startTime']&&&$endTime我可以建议,与其编写一个测试存在性并返回bool的函数来返回记录,不如稍后通过这种方式来测试是否没有返回记录,但如果有,您可以根据需要使用它们。正如Alvin Wong建议的那样,您可以在sql中使用
BETWEEN
,这样您就可以得到这样的结果

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

为什么不在SQL语句的
WHERE
子句中简单地使用
BETWEEN
=
,并使用输出行计数呢?@AlvinWong我会试试it@AlvinWong它是有效的,写下来作为答案来接受它
$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);
    }
}