Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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?

share|improve this question
add comment

1 Answer

up vote 1 down vote accepted

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++;
};
share|improve this answer
 
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? –  Rafael Magnvs Nov 16 '13 at 16:16
 
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. –  misterion Nov 16 '13 at 16:23
2  
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. –  Aluan Haddad Nov 16 '13 at 16:30
1  
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. –  JAL Nov 16 '13 at 16:43
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.