php_beginner
php_beginner

Reputation: 47

PHP Foreach multiple arrays write to csv file

I have the following data repeated five times and want to return the array and write the array to my csv file:

    <strong>Inventory number:</strong>
    <input name="inv[]" type="text" size="10" id="inv[]"/>
    <strong>Description:</strong>
    <input name="des[]" type="text" size="30"id="des[]"/> 

    <strong>Inventory number:</strong>
    <input name="inv[]" type="text" size="10" id="inv[]"/>
    <strong>Description:</strong>
    <input name="des[]" type="text" size="30"id="des[]"/> 

I did a foreach:

for ($i = 0, $rowcount = count($_POST['inv']); $i < $rowcount; $i++)
    {
$inv = $_POST['inv'][$i];   // get inventory
$des  = $_POST['des'][$i]; // get description
      }

then have a write command:

if(empty($errorMessage))
{
    $fs = fopen("data.csv","a") or die("Unable to open file for output");
    fwrite($fs,$sn . ", " . $givenname . ", " . $mail . ", " . $uid . ", " . $inv . ", " . $des . ", " . date("Y.m.d H:i:s") . "\n");
    fclose($fs);

    $destination_url = "receipt.php";

    header("Location: $destination_url");
    exit;
}

but it only writes the last array to the csv file.

Can you help? Thanks

Upvotes: 0

Views: 696

Answers (1)

user4035
user4035

Reputation: 23719

You must traverse through the array and write every record into the file:

<?php
if(empty($errorMessage))
{
    $rowcount = count($_POST['inv']);
    $fs = fopen("data.csv","a") or die("Unable to open file for output");
    for ($i = 0; $i < $rowcount; $i++)
    {
        $inv = $_POST['inv'][$i];   // get inventory
        $des  = $_POST['des'][$i]; // get description
        fwrite($fs, $sn . ", " . $givenname . ", " . $mail . ", " . $uid . ", " . 
            $inv . ", " . $des . ", " . date("Y.m.d H:i:s") . "\n");
    }

    fclose($fs);
}

$destination_url = "receipt.php";
header("Location: $destination_url");

Upvotes: 1

Related Questions