1

I need a PHP script which will update existing MySQL table getting data from a CSV. Table field hasweb need to be updated comparing a field consultant_id.

So MySql query should be

UPDATE user_data 
SET hasweb="something" 
WHERE consultant_id = "something";

Please help me to write a PHP script which can execute this query as many times as needed, depending upon CSV data.

0

3 Answers 3

4

I have written little php scripts to accomplish this many times and there are many ways go to about it:

The best according to my experience is to use CSV functions provided by PHP, take a look at fgetcsv(), because manually opening file and reading it line by line and parsing can cause complications.

Now you just loop through all the rows in csv and prepare query dynamically and execute it, for example (assuming that column 0 has IDs and column 1 has "hasweb")

<?php
    if (($handle = fopen("input.csv", "r")) !== FALSE)
    {
        while (($data = fgetcsv($handle, 1000, ",")) !== FALSE)
        {
            mysql_query(UPDATE user_data SET hasweb="{$data[1]}" WHERE consultant_id = "{$data[0]}"); 
        }
    fclose($handle);
    }
?>

Hope that helps. If still stuck, Please ask me :)

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

2 Comments

Hey @BlackDivine - why are you using 1000 for the length in that fgetcsv function? I'm trying to do the same thing that the original poster wanted to do and I'm curious. Thank you!!
Because it's a safe limit, unless you have a line longer than 1k chars. Be aware that second parameter (1000 in this case) is not the length of whole file, but a single line. Quoting official php docs "Must be greater than the longest line (in characters) to be found in the CSV file (allowing for trailing line-end characters). It became optional in PHP 5. Omitting this parameter (or setting it to 0 in PHP 5.0.4 and later) the maximum line length is not limited, which is slightly slower. "
1

You can use php function fgetcsv.

you can get all data from CSV file into php by using this function. for example,

$row = 1;
if (($handle = fopen("your_file.csv", "r")) !== FALSE) {
  while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
    $num = count($data);
    echo "<p> $num fields in line $row: <br /></p>\n";
    $row++;
    for ($c=0; $c < $num; $c++) {
        $SQL = 'UPDATE table_name SET col1=val1 WHERE con1';
        execute($SQL); 
    }
}
fclose($handle);
}

Comments

1

see this function: http://www.php.net/manual/zh/function.fgetcsv.php

Comments

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.