duanpei8518 2017-02-08 16:09
浏览 79
已采纳

如何防止从csv到mysql的重复插入

How to prevent insert if email exist

if (isset($_REQUEST['btn_import']))
{
    $filename = 'Database.csv';
    $fp = fopen($filename, "r");
    while (($row = fgetcsv($fp, "40", ",")) != FALSE)
    {
        $sql = "INSERT INTO excel (name,email,phone_no) VALUES('" . implode("','", $row) . "')";
        if (!$conn->query($sql))
        {
            echo '<br>Data No Insert<br>';
        }
    }
    fclose($fp);
}

ps. this code its from stackoverflow

  • 写回答

1条回答 默认 最新

  • doudi4621 2017-02-08 16:14
    关注

    You have several ways to do this.

    1. Clean your csv before trying to insert : $csv[$row[$emailColId]] = $row for example
    2. Before every insert, use SELECT COUNT(*) WHERE email = $email
    3. In your table definition, add an Index on email, set it to UNIQUE and deal with query() returning true / false or exceptions thrown

    To me, the best choice would be the 3rd point.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?