Insert and update error

I have written this code to upload data to mysql database using csv

This PHP page should insert if its a new record else if its the old record it should update

But here only insert function is working not upload function

please check what is the error and let me know

<?php //Upload File if (isset($_POST['submit'])) { if (is_uploaded_file($_FILES['filename']['tmp_name'])) { echo "

" . "File ". $_FILES['filename']['name'] ." uploaded successfully." . "

"; echo "

Displaying contents:

"; readfile($_FILES['filename']['tmp_name']); } //Import uploaded file to Database $handle = fopen($_FILES['filename']['tmp_name'], "r"); while (($data = fgetcsv($handle, 2000, ",")) !== FALSE){ $Sql=mysql_query("select * from personal where id ='$id'"); if(mysql_num_rows($Sql) > 0) { $import="update test set `name`='$data[1]', `gender`='$data[2]', `designation`='$data[3]' where id='$data[0]'"; mysql_query($import) or die(mysql_error()); } else { $import="insert into test set `name`='$data[1]', `gender`='$data[2]', `designation`='$data[3]', `id`='$data[0]'"; mysql_query($import) or die(mysql_error()); } } fclose($handle); print "Update done"; //view upload form }else { print "Upload new csv by browsing to file and clicking on Upload
\n"; print ""; print "File name to import:
\n"; print "
\n"; print ""; } ?>

You can take all the confusion out of your code by using an Insert on Duplicate key update sql statement

http://dev.mysql.com/doc/refman/5.0/en/insert-on-duplicate.html

But at first glance your insert statement is constructed wrong

[php] $import=“insert into test set name=’$data[1]’, gender=’$data[2]’, designation=’$data[3]’, id=’$data[0]’”;[/php]

You coded it like an Update statement. It should look like this.

[php] $import=“insert into ‘test’ (‘name’, ‘gender’,‘designation’) VALUES (’$data[1]’,’$data[2]’,’$data[3]’)” ;[/php]

Below will be the combined insert/update statement.

[php] $import=“insert into ‘test’ (‘id’,‘name’, ‘gender’,‘designation’) VALUES (’$data[0]’,’$data[1]’,’$data[2]’,’$data[3]’) ON DUPLICATE KEY UPDATE ‘name’=’$data[1]’,‘gender’ = ‘$data[2]’, ‘designation’ = ‘$data[3]’” ;[/php]

This line in your code doesn’t make sense, you’re trying to get a record from a “personal” table then you try to update the “test” table based on results being returned from the personal table.

$Sql=mysql_query(“select * from personal where id =’$id’”);

Anyway I hope this helps… If you clarify the table names I might be able to re-write it for you.

Sponsor our Newsletter | Privacy Policy | Terms of Service