Write HTML form input to csv file with PHP-ThrowExceptions

Exception or error:

I have a PHP form in which the user enters their data. On submit, it should open an existing CSV file and append some of the data. I have tried a number of things, but here is the most recent code I am currently working with:


<head><title>Design Request</title></head>
<title>Design Request</title>     

  <form action="test2.php" method="POST">
    <fieldset align="left">
    <legend>Executive Sponsor Form</legend>
    <p><i>To be completed by the executive sponsor</i></p>
        <td>Name:</td><td><input type="text" name="SPONSOR_NAME" size="40" /></td>
        <td>Position:</td><td><input type="text" name="SPONSOR_POSITION" size="40" /></td>
        <td>Telephone Number:</td><td><input type="text" name="SPONSOR_TELEPHONE_NUMBER" size="40" maxlength="11" /></td>
        <td>Email Address:</td><td><input type="email" name="SPONSOR_EMAIL" size="40" /></td>
        <td>Budget :</td><td><input type="checkbox" /><input type="text" name="BUDGET" size="37" maxlength="6" placeholder="budget code" /></td>
        <td>Aligned to which<br> priority:</td><td><input type="text" name="PRIORITIES" size="40" /></td>
        <td> Benefit to Business:</td><td><textarea cols="42" rows="10" name="BENEFIT"></textarea></td>
    <input type="submit" value="Submit">


    <title>Your (Ref No: ["SPONSOR_NAME"]) has been submitted.</title>        
    $data = array("" . ',' . "SPONSOR_NAME" . ',' . "" . ',' . "" . ',' . "SPONSOR_EMAIL" . ',' . "PRIORITIES" . );

    $fp = fopen("/var/www/testdb.csv","w");
    foreach ($data as $fields){
      fputcsv($fp, $fields);

Some of the fields are entered on one worksheet where as some are entered on another one thats why I have the array with some empty fields (I want data in column B E and F) the other columns will contain data from another form.

How to solve:

since you have already constructed your array for your data, you can just write the line to the file using PHP’s implode() function

  $data = array("" . ',' . "SPONSOR_NAME" . ',' . "" . ',' . "" . ',' . "SPONSOR_EMAIL" . ',' . "PRIORITIES" . );

  $file = "/var/www/testdb.csv";          //file to append to
  $current = file_get_contents($file);    //open the file
  $current .= "\n" . implode(",",$data);  //add line-break then comma separated array data
  file_put_contents($file, $current);     //append new content to file

if you need to fill in those blanks in your data from another form, you will have to reopen the file, extract the last line of data, explode() it to an array, fill in the missing data and then overwrite the original line in the csv… I would not recommend this because a different user could submit the first part of a form and then append their new data to an incorrect line of the csv… in this case you should really take the advice of @symcbean and use a proper database.

Leave a Reply

Your email address will not be published. Required fields are marked *