How to Read a File and Write Its Contents to a Column of a MySQL Table Using PHP

PHP


In this article, we show how to read a file and write its contents to a column of a MySQL table using PHP.

So we're taking a file, reading its contents, and writing it to a column of a MySQL table.

If you want to find out how to load a comma-separated values (CSV) file into a MySQL table using PHP, see How to Load a CSV File Into a MySQL Table Using PHP.

In this article, we simply show how to read the contents of a plain file and insert the contents of the file into a column of a MySQL table.

So let's say we have the following file: Comment.

In this file is the line, "This tutorial was good".

So how do we read this file and write its contents to a column of a MySQL table?

The following PHP code shows how to do it below.



So the code is very simple. First we connect to the datbase.

We then create a variable named $fileread that reads the contents of the file named file-to-read.txt. This variable now holds the contents of this file.

We then create a mysql_query() function to insert into the MySQL column named column_name the varible $fileread, which has the contents of the file we read.

We then close the database connection.

And this is all that is required to read the contents of a file and write it into a column of a MySQL table.

Example

So using the example of the file, comment-by-user.txt, that I created which contains, "This tutorial was good" and running it with the PHP code, with the correct table name and file name added, along with the data in table form, we get the following result below.

Actual PHP Output