【问题标题】:Import csv with php to mysql and用 php 将 csv 导入 mysql 和
【发布时间】:2019-08-06 11:13:52
【问题描述】:

您好,我想通过 php 将我的 folder.csv 导入 mysql。但我需要

“用文件替换表数据的复选框'ON'”

,但我不知道怎么做。 此请求 sql 有效,但我想将他转换为使用 php 导入并自动执行一些操作

 $commande="mysql -u root -p mydb LOAD DATA LOCAL INFILE 'D:/Programmes/wamp64/www/Importcsv/imports/test.csv' INTO TABLE myTable FIELDS TERMINATED BY ';' ";
    exec($commande);

所以事实上我需要感谢 php import my file.csv 我真的需要 "Check box 'ON' to replace table data with file" 。我的 id 是一个主键和 a.i 所以我需要有这个选项来修改我在每个 id 中的数据。

祝你有个美好的一天

【问题讨论】:

    标签: php mysql csv import


    【解决方案1】:

    我建议您对特定文件进行临时上传,这是上传的 HTML 表单:

    <table width="600">
        <form action="<?php echo $_SERVER["PHP_SELF"]; ?>" method="post" enctype="multipart/form-data">
            <tr>
                <td width="20%">Select file</td>
                <td width="80%"><input type="file" name="file" id="file" /></td>
            </tr>
            <tr>
                <td>Submit</td>
                <td><input type="submit" name="submit" /></td>
            </tr>
        </form>
    </table>
    

    用户$_FILES["file"]["tmp_name"] 获取该文件并像这样解析它:

    上面的行会抓取你的文件,你必须像这样解析它(我会为你做一个函数):

    function parseCSV($_FILES["file"]["tmp_name"]){
        $csv = [];
        $lines = file($file, FILE_IGNORE_NEW_LINES); //this will ignore new lines, 
        //meaning that it will jump to the next row at a new line
        foreach ($lines as $key => $value) {//go trough each line with the foreach loop
            $csv[$key] = str_getcsv($value, ';');//this will delimit each column of a row by 
        //';'(semicolon) it might aswell be whatever your need it to be
        }
        //use the block below to see if the CSV was parsed within an array
        //echo '<pre>';
        //print_r($csv);
        //echo '</pre>';
        //die;
         return $csv;
    }
    

    解析文件后(在数组中查看),您可以查看 W33 教程,了解如何在表中插入值 w3schools tutorial

    希望对您有所帮助! 祝你有美好的一天!

    【讨论】:

    • 用你的代码我应该是插入或更新不?我与我的 db 有联系。使用您的代码,您并没有真正导入您使用插入或更新 sql 请求,但出于某种原因,我想使用此 sql 请求导入,例如更优化和最简单。
    • 这确实是我所描述的插入,但这样做更安全,您可以访问要插入的数组,并且可以根据需要格式化每一列(即数量column 可能是 float/double/string/int 并且它可能有不同的分隔符,如空格、逗号或点)
    • 我不知道我是否需要像 INSERT 那样准备 tis 请求,或者如果你知道我可以执行请求,我只是做一个查询可能会很好
    • 是的,我明白,但是当我向 phpmyadmin 发出请求时,如果我能写一个简单的导入请求,我将不胜感激
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-02-04
    • 2013-08-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多