7

I've got a PHP routine that processes a form and outputs the values to a CSV file. I'm using array_keys() to create the header row (skipped if there is one). Everything works perfectly except the final header term is "submit" because, of course, my form includes a Submit button. So the data ends up looking like this:

name,email,cell,dob,study,submit
"Temp One",fred@gmail.com,646-325-1111,1995-03-31,8,Submit
"Temp Two",tom@gmail.com,646-325-2222,1995-03-31,4,Submit

How do I omit the submit button both from the header and the data?

Here's my code:

if(isset($_POST['submit'])) {
    $data = array_values($_POST); // get only values
    $headers = array_keys($_POST); // keys are headers 
    if( $fp = fopen('data.csv','a+')) {
        $line = fgets($fp);
        if(!$line == $headers) {
                fputcsv($fp, $headers);
                fputcsv($fp, $data);
        }
        else
        {
            fputcsv($fp, $data);
        }
        fclose($fp);
        header('Location: thanks.php'); 
    }
}
Elrond_EGLDer
  • 47,430
  • 25
  • 189
  • 180
Joe Lowery
  • 540
  • 9
  • 24
  • There is some use in reading through the topics of the PHP manual when you plan to use the language a bit more. For example the section about variables and array: http://php.net/variables http://php.net/arrays – hakre Jul 12 '13 at 23:04

3 Answers3

12

Remove it from the array...

$post = $_POST;
unset($post['submit']);
$data = array_values($post); // get only values
$headers = array_keys($post); // keys are headers 
Matt S
  • 13,731
  • 4
  • 45
  • 70
1

Drop the name from the Submit button in your html

and instead of

if(isset($_POST['submit']))

use

if($_SERVER["REQUEST_METHOD"] == "POST")
Orangepill
  • 23,853
  • 3
  • 38
  • 62
0

array_pop() will remove the last element of an array:

$data = array_pop(array_values($_POST)); // get only values
$headers = array_pop(array_keys($_POST)); // keys are headers
michi
  • 6,486
  • 4
  • 31
  • 52