1

I have a CSV file I loop thru to get an array od data that looks like this:

    $data[0]['StockNumber']

This array as 400 different rows. I need to compare these values against my database and do 3 action.

Select data from my database and return as an object.

If $data[0]['stockNumber'] exist in my DB, I want to update my database. If $data[0]['stockNumber'] doesn't exist, I want to add to my database.

After that, if a stock number exist in my DB but not in my CSV, I want to delete from my DB.

How can I loop this?

here is the code I am using

        function ImportCSV2Array($filename)
{
    $row = 0;
    $col = 0;

    $handle = @fopen($filename, "r");
    if ($handle) 
    {
        while (($row = fgetcsv($handle, 4096,'|','"')) !== false) 
        {
            if (empty($fields)) 
            {
            $fields = $row;
            continue;
        }

             foreach ($row as $k=>$value) 
            {
            $results[$col][$fields[$k]] = $value;
        }
            $col++;
                unset($row);
        }
        if (!feof($handle)) 
        {
            echo "Error: unexpected fgets() failn";
        }
        fclose($handle);
    }

    return $results;
}

$csvArray = ImportCSV2Array($filename);
print_r($csvArray[4]['StockNumber']);

"SELECT StockNumber FROM my_table"
$result = $conn->query($sql);

Now, how can I check all the valus from $result against value in $results

1
  • writing code would be a good start... Commented Dec 3, 2015 at 15:09

1 Answer 1

1

IMO Your approach to solve this task is wrong.

Here's how I would do this.

1- Create a temp table in mysql, parse the CSV file & add the file data into the temp table.

2- Run a single query updating quantities or whatever if the ids exists in the original table.

update `original_table` `ot` set `ot`.quantity = `t`.`quantity` 
inner join temp_table `t` on ot.id = t.id 

3- Run a single query deleting products that does not exists in my temp table

delete from `original_table` WHERE `id` NOT IN(SELECT `id` FROM `temp_table`)

4- Run a single query adding products that exists in my temp table but not in my original table.

eg: INSERT INTO `original_table` (`id`, `name` ...) SELECT `id`, `name` ... FROM `temp_table` WHERE `temp_table`.`id` NOT IN(SELECT `id` FROM `original_table`)

This approach your entire process would take a few seconds.

Ofcourse this is just an example, try with local data first to see if everything works fine before putting this into production.

Sign up to request clarification or add additional context in comments.

1 Comment

sounds promissing. I will try that.

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.