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