Chris
Chris

Reputation: 69

Is there a way to have php check a csv file for duplicate value before inserting a new row?

I have searched and searched for a simple solution and I am afraid there may not be a simple one after all of my research...

Here is what I have... All users who are authorizing the twitter app are opting in to being added to a list (the csv file) to be followed by other users. Its a spot for users with the same interest to follow each other. Here is what I am trying to achieve. I have users authorizing their twitter account which inserts their username into a csv file using php.

Users can only access the page once they have inserted their twitter which I am using oauth to authorize is an actual twitter account.

However, if the user visits the page again, they will be inserted into the csv file again. I have very simple logic to prevent an insert if they refresh the page and whatnot (when the $username value is blank).

<?php
if ($username == '') //check if $username is blank so empty row isnt inserted
{}
else{
$cvsData = $username."\n";
$fp = fopen("Twitter.csv","a"); // $fp is now the file pointer to file $filename
if($fp){
fwrite($fp,$cvsData); // Write information to the file
fclose($fp); // Close the file
  }
}
?>

There is no header row in the file. It is just a single column of twitter handles. I know the logic sounds kind of simple:

open csv file
loop through each row searching for value of $username
if $username exists - close file
else append $username
close file

Unfortunately I am learning still and having trouble finding a solution. Perhaps its the loop part that I need help with? Or a starting point. I am not at all looking for the code to make this happen though that would save me time. I'm not afraid to learn it - just having trouble finding the solution on my own. Any help is very much appreciated!

Upvotes: 2

Views: 1932

Answers (1)

Gung Foo
Gung Foo

Reputation: 13558

array_unique — Removes duplicate values from an array

Put the the values from the csv into an array and run array_unique() on it.

Upvotes: 1

Related Questions