2011-01-23 68 views
-1

如果我從表單中獲取數據,我可以使用下面的代碼來檢查重複項,但是當我導入csv文件時,我如何檢查重複項。在PHP中導入CSV時檢查重複內容

這裏select(=)只會有一個值,但在excel中如果有25行,我該怎麼做?

$check = mysql_query("SELECT * FROM table WHERE x= '$Thd'"); 

if ($x) 
{ 
    if(mysql_num_rows($check) != 0) 
    { 
    header('location:nw.php?msg=cat exists'); 
    } 
    else 
    { 

    )"; 

在此先感謝。任何幫助表示讚賞。

回答

0

mysql_query返回一個資源對象,它可以迭代獲取每行數據。請參閱the resource documentation中的示例進行討論。

+0

我需要在插入前檢查它。 – fvgf 2011-01-23 14:34:03

+0

$ linemysql = implode(「','」,$ linearray); $ newlinemysql = str_replace('\ n',「,$ linemysql); 如果($ addauto){ 開關($ databasetable){ 情況下(「DocumentID」): $ duplicatevals =「DocumentID = VALUES(DocumentID)」; break; } $查詢=「插入到$ databasetable值(」,」 $ newlinemysql」) ON DUPLICATE KEY UPDATE $ duplicatevals」; }否則{ $查詢=「插入到$ databasetable值(‘$ linemysql’) ON DUPLICATE KEY UPDATE $ duplicatevals」; }我用上面的腳本,但我得到的錯誤 $ duplicatevals =「DocumentID = VALUES(DocumentID)」; 意外= – fvgf 2011-01-23 15:00:10

1

你可以參考這個

Fgetcv

得到一個數組,然後檢查

0

好了,所以,你在數據從CSV文件拉動。我通常使用fopen/fgets而不是PHP的fingety fgetcsv(),但無論如何,你需要做的檢查重複值的方法與上面的類似。舉例來說,如果我知道哪些字段是唯一字段會更容易,但是:

$check = mysql_query("SELECT `x` FROM `table` WHERE `x` = '$uniquecsvfield' LIMIT 1"); 
//LIMIT 1 will stop it from searching for more, since you only need to know if one result exists. 
//If you don't do LIMIT 1 then it will go through the whole table even if it finds one. 
//Can also do 'WHERE x = $uniquecsvfield1 AND y = $uniquecsvfield2, whatever, depending on how 
//many Fields need to be unique 

if(mysql_num_rows($check) == 0) //If no rows are returned 
{ 
    mysql_query("INSERT INTO `table` VALUES blah blah blah"); //Insert 
} 
//Since you're gonna be processing the whole file, probably don't need to do anything if there is a 
//duplicate, it just won't insert it. 
//You could do an else that echo out "Duplicate found" or whatever