Best way to avoid duplicate entry into mysql database

后端 未结 4 1056
孤街浪徒
孤街浪徒 2020-11-22 09:53

I have a table with 3 columns - id (pk), pageId (fk), name. I have a php script which dumps about 5000 records into the table, with about half being duplicates, with same pa

4条回答
  •  囚心锁ツ
    2020-11-22 10:17

    From a mysql point you can do

    alter table YOURTABLE add unique index(pageId, name);
    

    If your wording is correct and you want to do it from php you can do

    $already_done = array();
    foreach ($records as $record)
    {
       $unique_hash = md5($record['name'].$record['pageId']);
       if (!in_array($unique_hash, $already_done))
       {
          $already_done[] = $unique_hash;
          // sql insert here
       }
    }
    

    either way those should do you just fine.

提交回复
热议问题