简体   繁体   中英

insert data from a csv file into sql server database using php

I am getting an error while inserting although my filename and location are properly set..Any solution? Thanks in advance...Here are my codes:

// path where your CSV file is located
define('CSV_PATH','C:\xampp\htdocs\form');

// Name of your CSV file
$csv_file = CSV_PATH . "test.csv"; 


if (($handle = fopen($csv_file, "r")) !== FALSE) {
   fgetcsv($handle);   
   while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
        $num = count($data);
        for ($c=0; $c < $num; $c++) {
          $col[$c] = $data[$c];
        }

 $col1 = $col[0];
 $col2 = $col[1];
 $col3 = $col[2];

 $query = "INSERT INTO csvTable(ID,Name,city) VALUES ('".$col1."','".$col2."','".$col3."')";
 $params = array();
 $options =  array( "Scrollable" => SQLSRV_CURSOR_KEYSET );
 $stmt = sqlsrv_query($conn, $query, $params, $options ); 
 }
    fclose($handle);
 }

echo "File data successfully imported to database!!";
//mysql_close($connect);
?>

Error Message: Warning: fopen(C:\\xampp\\htdocs\\formtest.csv): failed to open stream: No such file or directory in C:\\xampp\\htdocs\\form\\upload.php on line 15

Add backslash('\\') after Form in define value

define('CSV_PATH','C:\xampp\htdocs\form');

Change TO

define('CSV_PATH','C:\xampp\htdocs\form\');

OR

Add backslash('\\') before your CSV file name

// Name of your CSV file
$csv_file = CSV_PATH . "test.csv"; 

Change to

$csv_file = CSV_PATH . "\test.csv"; 

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