简体   繁体   English

使用PHP将csv文件导入mysql

[英]Importing csv file into mysql using PHP

I am currently trying to import data into mysql through a csv file using PHP, while doing so i get the following error:我目前正在尝试使用 PHP 通过 csv 文件将数据导入 mysql,同时我收到以下错误:

upload file name: test.csv You have an error in your SQL syntax;上传文件名:test.csv 您的 SQL 语法有错误; check the manual that corresponds to your MySQL server version for the right syntax to use near 'name,Country,Currency) values('Company name','Country','Currency')' at line 1检查与您的 MySQL 服务器版本相对应的手册,以获取在第 1 行的 'name,Country,Currency) values('Company name','Country','Currency')' 附近使用的正确语法

So please help me out in solving the above error Thanks in advance所以请帮我解决上述错误提前致谢

This is the code which i am using这是我正在使用的代码

<?php
ini_set('display_errors', 1);
error_reporting(E_ALL);
$db_host = 'localhost';
$db_user = 'root';
$db_pwd = '';

$database = 'automation';
$table = 'company';

if (!mysql_connect($db_host, $db_user, $db_pwd))
    die("Can't connect to database");

if (!mysql_select_db($database))
    die("Can't select database");


    if(isset($_POST['submit']))
    {
         $fname = $_FILES['sel_file']['name'];
         echo 'upload file name: '.$fname.' ';
         $chk_ext = explode(".",$fname);

         if(strtolower(end($chk_ext)) == "csv")
         {

             $filename = $_FILES['sel_file']['tmp_name'];
             $handle = fopen($filename, "r");

             while (($data = fgetcsv($handle, 1000, ",")) !== FALSE)
             {
                $sql = "INSERT into company(Company name,Country,Currency) values('$data[0]','$data[1]','$data[2]')";
                mysql_query($sql) or die(mysql_error());
             }

             fclose($handle);
             echo "Successfully Imported";

         }
         else
         {
             echo "Invalid File";
         }   
    }

    ?>
    <h1>Import CSV file</h1>
    <form action='<?php echo $_SERVER["PHP_SELF"];?>' method='post' enctype="multipart/form-data">
        Import File : <input type='file' name='sel_file' size='100'>
        <input type='submit' name='submit' value='submit'>
    </form>

If the column company name is two words you have to wrap it in backticks.如果列company name是两个词,则必须用反引号将其括起来。

If there are quotes in the data (or god forbid, some kind of SQL injection) you're basically doomed.如果数据中有引号(或上帝保佑,某种 SQL 注入)你基本上注定要失败。

mysql_* is deprecated and not safe to use. mysql_*已弃用,使用不安全。 You should look into PDO or MySQLi prepared statements.您应该查看 PDO 或 MySQLi 准备好的语句。

And, if this is a one-time upload consider using phpMyAdmin to import your CSV.而且,如果这是一次性上传,请考虑使用 phpMyAdmin 导入您的 CSV。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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