Update content from csv to mysql database

here is a mysql database named: example which has a table named: products it have fields: products_model and products_image. the model field is unique.

now i have a csv file named data.csv. which have two column products_model and products_image.i use the following code. but it doesn’t update the data of the database.what’s wrong with my code?

 $fp = fopen("data.csv","r");
$length = 4096;
$fildDelineate = ',' ;
$dbhost="localhost";
$dbname="example";
$dbuser="root";
$dbpass="123";
$link  = mysql_connect($dbhost,$dbuser,$dbpass);
if (!$link) {
    die('Could not connect: ' . mysql_error());
}
mysql_select_db($dbname);

$databasetable  = 'products';

$counter = 1;

while($line = fgetcsv($fp,$length,$fildDelineate)){
    foreach($line as $key=>$value){

        $importSQL = "update products set products_image = '".$lineArray[1]."' where products_model = '". $lineArray[0].""";
        mysql_query($importSQL) or die(mysql_error());
    }
    $counter++;
}
fclose($fp);

data.csv:

have two column:

products_model  products_image
MG200MMS    dress/201247561673.jpg
MG400-32MB  dress/2012471141673.jpg
MSIMPRO dress/201247741673.jpg
DVD-RPMK    dress/2012471831673.jpg
DVD-BLDRNDC dress/2012474221673.jpg
DVD-MATR    dress/201112132056773.jpg

Where does $lineArray[0] & $lineArray[1] come from?

Double quote instead of single at end of sql $lineArray[0].“”“; as well, should be $lineArray[0].”'";

i am sorry. its $line[0] and $line[1]. those are from the data.csv

Try this variation…

while($line = fgetcsv($fp,$length,$fildDelineate))
{
	$importSQL = "update products set products_image = '".$line[1]."' where products_model = '". $line[0]."'";
    mysql_query($importSQL) or die(mysql_error());
    $counter++;
}

For info, the ‘c’ in csv stands for comma, your data needs some commas :slight_smile:

it’s ok now. thank you. why your code don’t use foreach loop? the counter = 1 is out of the while loop. i don’t know why you don’t use foreach. thank u

some body knows why Lats code don’t use foreach loop?

Did you really need to use foreach?

What was the point of $counter? I didn’t see it being used.

i am sorry i don’t know why, could you give an explanation to me of your code. thank you