0

I am trying to add data to 2 different MySql tables through a CSV upload. I have been able to retrieve the information and upload part of the information on one table, but I am having issues sending data to the second table. I have come up with the following code:

$i = 0;
//Loop through the csv file
do {
    if ($data[0]) {

        //Store request information
        //Info for Request Table
        $requester_email = $data[0];
        $requester_name = $data[1];
        $client_name = $data[2];
        $client_country = $data[3];
        $opportunity_number = $data[4];
        $machine_quantity = $data[5];
        $severity = $data[6];

        //Store machine values
        //Info for Serial Numbers Table
        $serialType = array();
        $serialModel = array();

            $serialType[$i] = $data[7];
            $serialModel[$i] = $data[8];

    }
    $i++;
} while ($data = fgetcsv($handle,1000,",","'"));

I am having an issue with the array. I have only been able to store the serialType and serialModel from the last line in the csv file. For example, if the csv file has 3 lines of data:

( [0] => Empty [1] => Empty [2] => Last Value ok )

How come I am unable to store the other two values?

1 Answer 1

1

Just move

$serialType = array();
$serialModel = array();

before do in your script. While it is still inside the do loop it is just a initialize variable in do - while scope each iteration and clean it up.

$i = 0;

$serialType = array();
$serialModel = array();

while ($data = fgetcsv($handle,1000,",","'")) {
...
    $serialType[$i] = $data[7];
    $serialModel[$i] = $data[8];
    $i++;
};
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks @misterion, you are correct! One more doubt on the subject, how come [0] => Still Empty? All the values are being stored starting from [1].. Why is that?
Look`s like your csv file first line can be empty or not contains 7,8 columns in it. Just try to debug it and add var_dump($data) in your loop and look at first line output.
Actually variables defined in PHP functions do not respect block the scope of control structures and their associated blocks and remain accessable to the function after their defining block has completed.
Yes, like Aluan says there is not any block scope like that in PHP. The real answer is that the arrays were being initialized inside the loop, which was wiping their content with each iteration.

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.