Home > Enterprise >  Add a column header row if not exist in PHP
Add a column header row if not exist in PHP

Time:04-28

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,zip\r\n";
$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 . "\r\n";
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";
?>
...

CodePudding user response:

From https://www.php.net/manual/es/function.fopen.php.

First add header then add with "a"

$fh = fopen("a.txt", "r ");
fwrite($fh, $header);
fclose($fh);

CodePudding user response:

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,yourzip\r";
$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 \r\n, also the end of the $savestring, \r not \r\n. With the \n removed the line spacing is single. With the \r\n the line spacing is double.

  •  Tags:  
  • php
  • Related