Uploading CSV file contents into database via PHP

<input name="csv" type="file" id="csv" />

user will upload a file that contains .csv extension.

the contents of the csv file should be like this:

10% 0% Enter questions here, it will grow automatically.% sadf% asdf% fds% asdf% fdas% 10
11% 0% Which is not the access specifier?% public% friend% protected% int% int% 10
15% 0% Enter questions here, it will grow automatically.% qwer% qwer% qwer% wer% er% 10
16% 0% Enter questions here, it will grow automatically.% asdf% asdf% adsf% asdf% asdf% 10
19% 0% Enter questions here, it will grow automatically.% 1% 2% 3% 4% 4% 1
21% 1% Enter questions here, it'll grow automatically.% 1% 12% 123% 1234% 1% 1


here, % is used for separating fields of the database and at the end of the line \n character i.e. new line in php is used so that the function will recognize each field and each record(row) separately.


on submit, the the is posted. on that posted page write following php code:

if ($_FILES['csv']['size'] > 0)
{
    //get the csv file
    $file = $_FILES['csv']['tmp_name'];
    $handle = fopen($file,"r");
    $data = array("");
    //loop through the csv file and insert into database
    do {
        if ($data[0]) {
            mysql_query("INSERT INTO tbl_master_quiz_question (quiz_id, question_id, question, option1, option2,option3,option4,correct_answer,marks) VALUES('".addslashes($data[0])."','".addslashes($data[1])."','".addslashes($data[2])."','".addslashes($data[3])."','".addslashes($data[4])."','".addslashes($data[5])."','".addslashes($data[6])."','".addslashes($data[7])."','".addslashes($data[8])."');
        }
    } while ($data = fgetcsv($handle,1000,"%","\n"));
}

the fgetcsv($handle,1000,"%","\n") function will split the CSV file contents by using % for each field and \n for each row. and it will be stored in $data array and is inserted through insert query into the database.

Comments