我有两个字段的表
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
答案 0 :(得分:1)
我可以建议,然后编写一个测试存在的函数并返回一个返回记录的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);
}
}