解决范围的重叠问题

荆轲刺秦王

问题场景:数据表中有开始ID和结束ID字段,这两个ID表示一段范围,现在我需要在每次插入新数据的时候,

我都要判断插入的数据是否和原有数据(原有的两个字段范围)有重叠的现象,如果有重叠则提示用户数据

不合法。

假设$startID和$endID 是接收用户输入的值。

mysql : 需要两条查询语句

SELECT * FROM 'tableName' where "$startID between start_id and end_id"

SELECT * FROM 'tableName' where "$endID between start_id and end_id"

这两条语句就是查询用户输入的数据是否在已有数据中,如果查询出来的有结果,那就是重叠,提示用户数据不合法。

使用ThinkPHP写:

//检查是否重叠

$checkStartID = $this->db->where("$startID between start_id and end_id")->select();

//echo $this->db->getLastSql();

//print_r($checkStartID);exit();

if($checkStartID) $this->error('开始ID重复','',true);

$checkEndID = $this->db->where("$endID between start_id and end_id")->select();

//echo $this->db->getLastSql();

//print_r($checkStartID);exit();

if($checkEndID) $this->error('结束ID重复','',true);


在接收用户输入信息的时候,一定要进行过滤,因为用户可能会输入任何东西。

在检查这个开始ID和结束ID的时候,除了要验证是 int 类型的,还要判断是否开始ID小于结束ID,

如果ID是事先生成好的,那么还要判断用户输入的这两个ID是否存在




猜你喜欢

转载自blog.csdn.net/qq_38350907/article/details/79208425