Skip to content
Advertisement

Add a column header row if not exist in PHP

I have an html form on my web site. When the form is filled out and the submit button is clicked the data is stored on my server in a csv text file. I want to add a column header row if it doesn’t exist. My code adds the header each time new data is entered whether it exists or not, even though I have an if statement that says add if the header row does not exist. What do I need to change so that the column header row only gets added if it doesn’t exist?

$fname = $_POST['fname'];
$address = $_POST['address'];
$city = $_POST['city'];
$yourzip = $_POST['yourzip'];
$header = "Name,address,city,ziprn";
$fp = fopen("protected/RaceName_2022-04-26_EntryList.txt", "a");
if (flock($fp, LOCK_EX)) {
    if(!file_exists($header)) {
    fwrite($fp, $header);
    }
$savestring = $fname . "," . $address . "," . $city . "," . $yourzip . "rn";
fwrite($fp, $savestring);
flock($fp, LOCK_UN);
}
else {
    echo "Error locking file!";
}
fclose($fp);
echo "Data has been saved in <b><i>protected</i></b> folder";
?>
...

Advertisement

Answer

After much struggling I got it right. First check if the file exists before opening, if not add the header. Here is the code that works as expected.

$exists = file_exists("protected/RaceName_2022-04-26_EntryList.txt");
$header = "fName,address,city,yourzipr";
$fp = fopen("protected/RaceName_2022-04-26_EntryList.txt", "a");
if (flock($fp, LOCK_EX)) {
if (!$exists) {
    fwrite($fp, $header);
}
$savestring = $fname . "," . $address . "," . $city . "," . 
$yourzip . "r";
fwrite($fp, $savestring);
flock($fp, LOCK_UN);
}

Note, the end of the $header string, r, not rn, also the end of the $savestring, r not rn. With the n removed the line spacing is single. With the rn the line spacing is double.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement