使用php mysql将csv文件导入数据库

时间:2017-10-10 12:23:58

标签: php mysql csv

我试图通过php导入数据库中的csv文件,但它无法正常工作。我不知道我在哪里弄错了我的代码

<?php
if (isset($_POST["submit"])) {
    $host = "localhost"; // Host name.
    $db_user = "root"; //mysql user
    $db_password = ""; //mysql pass
    $db = 'moodle'; // Database name.
    $conn = mysql_connect($host, $db_user, $db_password) or die(mysql_error());
    mysql_select_db($db) or die(mysql_error());


    $filename = $_FILES["file"]["name"];
    $ext = substr($filename, strrpos($filename, "."), (strlen($filename) - strrpos($filename, ".")));

    //we check,file must be have csv extention
    if ($ext == "csv") {
        $file = fopen($filename, "r");
        while (($emapData = fgetcsv($file, 10000, ",")) !== FALSE) {
            $sql = "INSERT into mdl_user(username,email) values('$emapData[0]','$emapData[1]')";
            mysql_query($sql);
        }
        fclose($file);
        echo "CSV File has been successfully Imported.";
    } else {
        echo "Error: Please Upload only CSV File";
    }
}
?>

这是表单代码

<form enctype="multipart/form-data" method="post" action="import_csv.php">
    <input type="file" name="file" id="file">
    <input type="submit" value="submit">
</form>

我没找到错误的地方

任何人都可以帮助我

提前感谢..

1 个答案:

答案 0 :(得分:0)

我创建了一个简单的应用程序来导入CSV,它还支持使用Laravel Framework,PHP Excel Lib和Laravel Excel Lib的东方语言,

如果你想看看,我可以推送到Github