1

I'm looping through a CSV to insert/update the name field of some records into a table. The script is mean't to insert the record and if it exists, only update the name field.

It's taking quite some time for larger CSV files so I was wondering if this code could be modified into a multiple INSERT query with an ON DUPLICATE KEY UPDATE command which will only update the name field of the record.

The CSV DOES NOT contain all the fields for the table, only the ones for the primary key and the name. And for that reason, REPLACE will not work for this case.

if (($handle = fopen($_FILES['csv']['tmp_name'], "r")) !== FALSE) {
        while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
            $title = 'Import: '.date('d-m-Y').' '.$row;

            # CHECK IF ALREADY EXISTS
            $explode = explode('-',$data[0]);
            $areacode = $explode[0];
            $exchange = $explode[1];
            $number = $explode[2];

            $update = "INSERT INTO ".TBLPREFIX."numbers SET
            area_code = ".$areacode.",
            exchange = ".$exchange.",
            number = ".$number.",
            status = 1,
            name = '".escape($data[1])."'
            ON DUPLICATE KEY UPDATE name = '".escape($data[1])."'";
            mysql_query($update) or die(mysql_error());
            $row++;


        }
        fclose($handle);
        $content .= success($row.' numbers have been imported.');
    }
4

1 回答 1

0

在开始插入之前打开一个事务,并在完成后提交它。这样数据库可以优化磁盘上的写操作,因为它发生在单独的内存空间中。在没有事务的情况下,所有单个查询都会一次自动提交,并对所有其他查询有效。

至少我希望你使用 InnoDB 作为存储引擎——MyISAM 不支持事务并且有其他明显的缺点。如果可能的话,你应该避免它。

于 2013-01-26T15:48:47.340 回答