将CSV导入MySql,如果重复,则更新选定的值

时间:2013-06-27 13:21:24

标签: php mysql

我正在尝试将csv文件导入到mysql-databse中,我希望uploadscript检查重复项,如果它发现任何它应该更新该行,但只有选定的值。我希望它更新除“first-seen”之外的所有值。 bssid是我唯一的识别者。我也有建议我应该将“addslashes”更改为一些更好的代码,但我不知道哪种方式最好做,有什么建议吗?

<?php 

//Count ap´s before import
$before = mysql_query("SELECT * FROM wifi");
$num_rows_before = mysql_num_rows($before);

if ($_FILES[csv][size] > 0) {

//get the csv file
$file = $_FILES[csv][tmp_name];
$handle = fopen($file,"r");

//loop through the csv file and insert into database
do {
    if ($data[0]) {
    $linesCount ++;
        mysql_query("INSERT INTO wifi (bssid, channel, privacy, ciper, auth, power, essid, latitude, longitude, first_seen, last_seen) VALUES
            (
                '".addslashes($data[0])."',
                '".addslashes($data[1])."',
                '".addslashes($data[2])."',
                '".addslashes($data[3])."',
                '".addslashes($data[4])."',
                '".addslashes($data[5])."',
                '".addslashes($data[6])."',
                '".addslashes($data[7])."',
                '".addslashes($data[8])."',
                '".addslashes($data[9])."',
                '".addslashes($data[10])."' 
            )
        ");
    }
} while ($data = fgetcsv($handle,1000,","));

//redirect
header('Location: index.php/ladda-upp?success=1&before=' . $num_rows_before); die;

}

//Catch argument from url
$arg_bef=$_GET['before'];

//Count ap´s after import
$after = mysql_query("SELECT * FROM wifi");
$num_rows_after = mysql_num_rows($after);

//Count new rows
$new_rows = $num_rows_after - $arg_bef;

//generic success notice
if (!empty($_GET[success])) { echo "<br><b>Resultat: Din fil har blivit importerad!</b><br><br>"; 

//echo stats
echo "Antal före import - ";
echo "$arg_bef";
echo "<br>";
echo "Antal efter import - ";
echo "$num_rows_after";
echo "<br>";
echo "Antal nya rader - ";
echo "$new_rows";
echo "<br>";
echo "Rader i CSV-fil - ";
} 

//Close connection to databse
mysql_close($connect) ; 

?>

2 个答案:

答案 0 :(得分:2)

你想要mysql的on duplicate key feature

http://dev.mysql.com/doc/refman/5.0/en/insert-on-duplicate.html

确保您在CSV中显示的字段上设置了密钥,例如:bssid可能有效。

而不是addslashes()使用mysql_real_escape_string(),但毫无疑问有人会指出mysql_函数已被弃用,很快就会删除,所以你应该至少使用mysqli。

答案 1 :(得分:1)

替代方案:REPLACE INTO的行为与INSERT INTO完全相同,只是在遇到重复的唯一值时会执行UPDATE