简体   繁体   中英

how to upload a csv file to mysql database using php

I have created a website which requires me to upload a csv file into the mysql database (Wamp server). Since I have never done this before a detailed answer with steps will be really helpful. I need the user to upload file using html input file option and then a php code to upload this file to mysql database. Iam using this code

<?php
$con=mysql_connect("localhost","","");
mysql_select_db("sg",$con);
define('CSV_PATH','C:/Users/mkutbudd/Desktop/');
$csv_file = CSV_PATH . "dum.csv";
if (($getfile = fopen($csv_file, "r")) !== FALSE) { 
        $data = fgetcsv($getfile, 1000, ",");
        while (($data = fgetcsv($getfile, 1000, ",")) !== FALSE) {
         $num = count($data); 
         for ($c=0; $c < $num; $c++) {
             $result = $data; 
             $str = implode(",", $result); 
             $slice = explode(",", $str);
             $col1 = $slice[0]; 
             $col2 = $slice[1];
             $col3 = $slice[2]; 
$query = "INSERT INTO dummy(dum1,dum2,dum3)
VALUES('".$col1."','".$col2."','".$col3."')";
$s=mysql_query($query, $con ); 
     }
   } 
  }
echo "File data successfully imported to database!!"; 
mysql_close($con); 
?>

There are an alternative way, if you have right to run system or execute functions and you have right to run mysql command, then you can use the mysql load data command: http://dev.mysql.com/doc/refman/5.1/en/load-data.html

Done.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM