0

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

1
  • 1
    You only have one fwrite command. Your $inv and $des variables get overwritten over and over again as the loop proceeds. What did you expect? Commented Jun 28, 2013 at 7:56

1 Answer 1

1

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");
Sign up to request clarification or add additional context in comments.

1 Comment

I was trying it told me I could in 6 mins lol - done now thanks again you saved the loads of time

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.