php - How to update table using LOAD INFILE?

464
$this->db->query("LOAD DATA LOCAL INFILE '".$file_path."' 

        INTO TABLE table1
        CHARACTER SET  utf8mb4
        FIELDS TERMINATED BY ','

        OPTIONALLY ENCLOSED BY  '\"' 
        LINES TERMINATED BY '\r\n' 

        IGNORE 1 LINES 

        (Email,Jurisdiction_Parish,Jurisdiction_Ward,Jurisdiction_Precinct,Personal_FirstName,
        Personal_MiddleName,Personal_LastName,Personal_NameSuffix,Residence_HouseNumber,Residence_HouseFraction,Residence_StreetDirection,
        Residence_StreetName,Residence_ApartmentNumber,Residence_City,Residence_State,Residence_ZipCode5,Residence_ZipCode4,Mail_Address1,
        Mail_Address2,Mail_City,Mail_State,Mail_ZipCode5,Mail_ZipCode4,Mail_Country,Personal_Sex,Personal_Race,Registration_PoliticalPartyCode,
        Personal_Age,Registration_VoterStatus,Registration_Date,Registration_Number,Personal_Phone,LastVoted,Residence_WalkListOrder,
        Favorability,Yard_Sign,Comments,Personal_NameOrder,voted,Rating,Custom_Variable1,Custom_Variable2,Custom_Variable3)
        SET cid =".$cid.", csvsheet_id=".$csvsheet_id
        );

The above code for insert the data of CSV into database but i want to update the existing records of database from CSV. So How can i modified the query so that it will work for UPDATE the records.

272

Answer

Solution:

  1. You must defined primary or unique key for fields, which are responsible for the equality of records
  2. You must addREPLACE keyword inLOAD INFILE statement
LOAD DATA LOCAL INFILE 'myfile' 
  REPLACE
  INTO TABLE table1
  CHARACTER SET  utf8mb4
  ................
71

Answer

Solution:

i used the below code for update the existing records of database.

 LOAD DATA LOCAL INFILE 'myfile' 
 REPLACE
 INTO TABLE table1
 CHARACTER SET  utf8mb4

But the problem is that in my CSV file i have only two column. When I Run the query it Updated the Records(voted column only) but others column has been blanked. Is is necessary to give all the column name with the data also..??

People are also looking for solutions to the problem: php - how to open file pdf in codeigniter

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.