比较数据库的时间值以停止重复条目

时间:2014-06-16 21:20:13

标签: php mysql

我将值插入数据库。

如果创建值的时间少于24小时,那么我就像这样插入

$stmt = $con->prepare('
    INSERT INTO taggedPlaces
    (id, created_time, place_id, city, country, latitude, longitude, state, street, zip, name)
    VALUES
    (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
');

foreach($graphObject['tagged_places']->data as $data) {
if (time() - strtotime($data->created_time) < 86400) {
      $stmt->execute(array(
       $data->id,
       $data->created_time,
       $data->place->id,
       $data->place->location->city,
       $data->place->location->country,
       $data->place->location->latitude,
       $data->place->location->longitude,
       $data->place->location->state,
       $data->place->location->street,
       $data->place->location->zip,
       $data->place->name
   ));
}
}

每当我返回页面时,它都会获取相同的条目并不断将它们添加到数据库中。

我想说点什么

if $data->created_time ==  any created_time value in the DB then don't add this value, 

as well as currently I am doing 

 if (time() - strtotime($data->created_time) < 86400)

确保它不会超过24小时。

如何添加此条件?

1 个答案:

答案 0 :(得分:1)

选项1: (已推荐)

id作为表格的主键taggedPlaces

ALTER TABLE taggedPlaces ADD PRIMARY KEY(id)

然后将insert语句更改为使用INSERT IGNORE,这将跳过重复插入。

选项2:

created_time中将taggedPlaces设为唯一字段:

ALTER TABLE taggedPlaces ADD UNIQUE(created_time);

然后,再次使用INSERT IGNORE跳过重复项。

选项3: (未推荐,但会有效)

在运行插入之前,请执行另一个查询以检查表中是否已有$data->created_time

$check = $con->prepare('
    SELECT id FROM taggedPlaces
    WHERE created_time = ?   
');

$check->execute(array($data->created_time));

if (count($check->fetchAll()) == 0) {
    // No duplicates found. Proceed...
}