-1

I am inserting record from CSV file to MySQL table; if any record already exists update that record and insert other records and if there is no match of the record insert all records.

Here is my code

<?php
    $connect = mysql_connect('localhost','root','root');
    if (!$connect) {
     die('Could not connect to MySQL: ' . mysql_error());
    }
    $cid =mysql_select_db('bizin490_devcredit',$connect);
    define('CSV_PATH', '/home/ubc/Documents/');
    $csv_file = CSV_PATH . "test.csv";
    $csvfile  = fopen($csv_file, 'r');
    $theData  = fgets($csvfile);
    $i = 0;
    while (!feof($csvfile)) {

     $csv_data[] = fgets($csvfile, 1024);
     $csv_array  = explode(",", $csv_data[$i]);
     $insert_csv = array();
     $insert_csv['name']  = $csv_array[0];
     $insert_csv['email'] = $csv_array[1];

     $query = mysql_query("select name from test where name='" . $insert_csv['name'] . "'");
     $count = mysql_num_rows($query);

     if ($count == 0) {
      $query = "INSERT INTO test(name,email)VALUES('" . $insert_csv['name'] . "','" .  $insert_csv['email'] . "')";

      $n = mysql_query($query, $connect);

      } else {

        $sql = "update test set email='".$insert_csv['email']."'";
        //echo "<pre>";print_r($sql);
        $qu  = mysql_query($sql);
        echo "<pre>";print_r($_POST);
      }
     $i++;
     //die;
   }
   fclose($csvfile);
   echo "File data successfully imported to database!!";
   mysql_close($connect);
?>
8
  • 1
    What is your issue??? Commented Dec 31, 2014 at 9:51
  • My Issues is , when it update records, it makes updated fileds balnk in database Commented Dec 31, 2014 at 9:53
  • $insert_csv['email'] may be null Commented Dec 31, 2014 at 9:55
  • Yes but how i am passing there value you can see in my code. Commented Dec 31, 2014 at 9:56
  • 1
    And LOAD DATA INFILE provides that functionality via [REPLACE | IGNORE] Commented Dec 31, 2014 at 10:00

1 Answer 1

0

Something like:

LOAD DATA INFILE '/home/ubc/Documents/test.csv'
REPLACE
INTO TABLE `test`
(name, email)
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.