I am getiing simple data from a txt file. Text file consist of list of countries. For e.g: America England Africa I am getting the content, explode it on line break and inserting into mysql. Till here, everything is going fine. Now what I actually want is that if i add two more countries in that list of txt file. So the data already got inserted should not insert again and only the two new lines should be added just.
2 Answers
If you have a PRIMARY KEY or UNIQUE KEY on a table then you can use INSERT IGNORE clause as:
e.g. If you have a UNIQUE KEY on column country then do:
INSERT IGNORE INTO table (country) VALUES ('America');
to forcefully remove duplicates see here
5 Comments
Noman Rizwan
i am using 'id' as primary key, what should be my query in that case?
Noman Rizwan
I fixed it! by using this query: REPLACE INTO table (id) VALUES ('1');
Omesh
you can add one more UNIQUE KEY on table to avoid duplicate values.
Noman Rizwan
Oh okay I will do this, now what I need is i delete any country from textfile so it should delete the entire row from mysql. How could it is possible?
Omesh
have a look at stackoverflow.com/questions/11557757/…
array_unique() is your friend here.
ex.
$filecontents = '...';
$countries = explode("\n", $filecontents);
$countries = array_unique($countries);
Then you can add the countries to your database. If you are talking about data that's already in the database do what @Omesh said.
2 Comments
Noman Rizwan
Yes REPLACE INTO done my work, now what I need is i delete any country from textfile so it should delete the entire row from mysql. How could it is possible?
octern
@NomanRizwan You should probably create a new question and ask there.