Hi
I am writing to a text file but end up having several duplicates in the text file, this is a basic program I am creating using PHP and HTML.
How is it possible to fwrite only when record exists. Thnx

<?php
$FirstName = $_POST['FirstName'];
$LastName = $_POST['LastName'];
$Email = $_POST['Email'];

$content= $FirstName."|".$LastName."|".$Email."\r\n";

$fp = fopen("member.txt","a");

if(!$fp) 
	{
    echo 'Error: Cannot open file.';
    exit;
	}
fwrite($fp,$content);
	{
	echo ("Hello, ".$_POST['FirstName']." ".$_POST['LastName']." to ICANS Members page.");
	}
fclose($fp);
?>

Recommended Answers

All 4 Replies

Hmmm....If i understood you correctly, you don't want any repeats, right? You can make a loop until endoffile and check for existance every time you enter the new data.

Note: This is beating the crap out of the problem and will be SLOW for large files.

$file = file('somefile');
$FirstName = $_POST['FirstName'];
$LastName = $_POST['LastName'];
$Email = $_POST['Email'];

$line_count_pre = count($file);
$content= $FirstName . '|' . $LastName . '|' . $Email;
$file[]=$content;
$line_count_post = count(array_unique($file));
unset($file);
if($line_count_post > $line_count_pre) {
  // write to the file
} else {
  // It is a duplicate
}

Hi thnx for replying
ShawnCPlus, using your script am still getting duplicates- all in one line.
Acute- I tried the endoffile as well but is not working.
Not sure what else to try, any more thoughts...
Cheers

Hi thnx for replying
ShawnCPlus, using your script am still getting duplicates- all in one line.
Acute- I tried the endoffile as well but is not working.
Not sure what else to try, any more thoughts...
Cheers

For future reference here when you say you tried an example and it didn't work post the code otherwise we don't know what we or you did wrong to fix it. If I had to guess I would say that when you're writing to the file you're not appending a newline.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.