dpzp5127 2014-06-16 21:20
浏览 32
已采纳

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

I am inserting values into a database.

If the time the values were created is less than 24 hours then I insert like this,

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

Everytime I return to the page it takes the same entries and continuously adds them to the database.

I would like to say something like

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)

to make sure it is not older then 24 hours.

How can I add this condition?

  • 写回答

1条回答 默认 最新

  • dougou7008 2014-06-16 22:12
    关注

    Option 1: (Recommeded)

    Make id the primary key for your table, taggedPlaces:

    ALTER TABLE taggedPlaces ADD PRIMARY KEY(id)
    

    Then change your insert statement to use INSERT IGNORE which will skip duplicate inserts.

    Option 2:

    Make created_time a unique field in taggedPlaces:

    ALTER TABLE taggedPlaces ADD UNIQUE(created_time);
    

    Then, again, use INSERT IGNORE to skip duplicates.

    Option 3: (Not recommeded, but will work)

    Prior to running your insert, perform another query to check if $data->created_time is already in the table:

    $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...
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 关于大棚监测的pcb板设计
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题