0

Hi I would like to know if there is a way to save a CSV file into a mysql table column using php? Please see that I am not seeking answers for importing/export data to & from table to csv file, I need to save the entire file after exporting from somewhere into a table. say for example:

id date       file
1 8/16/2022   abc.csv
2 7/16/2022   xyz.csv

I have everything till the point of data insertion. Just need someone to guide me on how to insert the file into table column using php, am using codeigniter.

5
  • You mean put the entire contents of the CSV into a database field? Yes, that's possible, just make sure that the field is large enough to hold the data. Commented Aug 16, 2022 at 15:04
  • Yes entire contents of the CSV into a database field, I am planning to use text as datatype for the file size isn't too large @HonkderHase Commented Aug 16, 2022 at 15:09
  • Then it's treated like any other string basically... Commented Aug 16, 2022 at 15:13
  • 1
    You can also use the LOAD_FILE() function. Commented Aug 16, 2022 at 15:25
  • It's not going to be usable in database but file_get_contents should allow you to do it. Commented Aug 16, 2022 at 15:25

1 Answer 1

2

If I understand your question correctly, it should be fairly simple. Assuming you already have a PDO object called $dbh, something similar to this should work (not verified):

$myStringContainingTheWholeFirstCsv = file_get_contents('abc.csv');
$sth = $dbh->prepare('INSERT INTO `my_table_name` (`my_column_name`) VALUES (:csv)');
$sth->bindParam(':csv', $myStringContainingTheWholeFirstCsv, PDO::PARAM_STR);
$sth->execute();
Sign up to request clarification or add additional context in comments.

2 Comments

Note that the size of the CSV file must be smaller than the max_allowed_packet MySQL option, and that option is effectively the lesser value set by the client and the MySQL Server.
Good point. file_get_contents() always holds the possibility of danger.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.