且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用PHP代码和HTML表单将excel(.csv)导入MySQL

更新时间:2023-01-21 13:24:43

我没有完全测试这个,但我没有看到任何原因它不工作。

I haven't fully tested this, but I don't see any reason why it wouldn't work.

<?php

if ( isset( $_FILES['userfile'] ) )
{
  $csv_file = $_FILES['userfile']['tmp_name'];

  if ( ! is_file( $csv_file ) )
    exit('File not found.');

  $sql = '';

  if (($handle = fopen( $csv_file, "r")) !== FALSE)
  {
      while (($data = fgetcsv($handle, 1000, ",")) !== FALSE)
      {
          $sql .= "INSERT INTO `table` SET
            `column0` = '$data[0]',
            `column1` = '$data[1]',
            `column2` = '$data[2]';
          ";
      }
      fclose($handle);
  }

  // Insert into database

  //exit( $sql );
  exit( "Complete!" );
}
?>
<!DOCTYPE html>
<html>
<head>
  <title>CSV to MySQL Via PHP</title>
</head>
<body>
  <form enctype="multipart/form-data" method="POST">
    <input name="userfile" type="file">
    <input type="submit" value="Upload">
  </form>
</body>
</html>


b $ b

当然,您需要先验证数据。

Of course you would need to validate the data first.