Search code examples
phpmysqliinnodbload-data-infile

LOAD DATA INFILE / PHP MySQLi / Adding additional columns/values for inputted & dealing with NULL values


I have been experimenting with LOAD DATA INFILE and there are a couple things I would like to be able to do. I'm not sure if they are possible, or if I may need to create a temporary table for the upload.

When a CSV file is uploaded/inputed in my application, I'd like to have an auto-incrementing column for the rows. In addition, I'd like to add a column value to each row identifying the user who uploaded the file.

I am using PHP/MySQLi on a InnoDB database.

I may also have empty strings for null values in my CSV files. Is there a simple way to input these values as NULL into the database?

Thanks for all your help!


Solution

  • to achieve what you want, you would need to programmatically pre-create the table first along with a triggers function prior to loading data into it.

    therefore, create the table first with triggers:

    example:

     CREATE TABLE foo (
        id INT NOT NULL AUTO_INCREMENT,
        fooitems TEXT,
        PRIMARY KEY (id)
     );
    
     CREATE TRIGGER fooblank2null
     BEFORE INSERT ON foo
     FOR EACH ROW
     SET NEW.fooitems=IF(TRIM(NEW.fooitems)='',NULL,NEW.fooitems);
    

    to test if the trigger works:

     INSERT INTO foo (fooitems)
     VALUES
     ('i'),(''),('am'),('foo'),(' '),('.');
    

    you can now load the data to the specific column.

    example:

     LOAD DATA
     INFILE 'foo.txt'
     INTO TABLE foo
     FIELDS TERMINATED BY ',' ENCLOSED BY '"'
     LINES TERMINATED BY '\n'
     (fooitems);