为csv文件的每个记录构建SQL查询

时间:2013-02-21 22:23:55

标签: php sql parsing csv

大家好日子,

说实话,我被困了......我想请求你的帮助。我面临的挑战看起来像这样: 1.将CSV文件上载到服务器。 2.打开CSV文件。 3.解析它,显示数据&为csv文件的每条记录构建一个sql查询。

现在,我的问题是第3步。我已经解析并在表中显示数据但是我在构建查询时失败了。感谢任何帮助!

这是我用来解析csv文件并显示数据的代码。我想请求您如何更改代码,以便为文件的每个记录创建和执行sql查询。

if ( $file = fopen( "upload/" . $storagename , r ) ) {

            echo "File opened.<br />";

            $firstline = fgets ($file, 4096 );
            //Gets the number of fields, in CSV-files the names of the fields are mostly given in the first line
            $num = strlen($firstline) - strlen(str_replace(";", "", $firstline));

            //save the different fields of the firstline in an array called fields
            $fields = array();
            $fields = explode( ";", $firstline, ($num+1) );

            $line = array();
            $i = 0;

            //CSV: one line is one record and the cells/fields are seperated by ";"
            //so $dsatz is an two dimensional array saving the records like this: $dsatz[number of record][number of cell]
            while ( $line[$i] = fgets ($file, 4096) ) {

                $dsatz[$i] = array();
                $dsatz[$i] = explode( ";", $line[$i], ($num+1) );

                $i++;
            }

            echo "<table>";
            echo "<tr>";
            for ( $k = 0; $k != ($num+1); $k++ ) {
                echo "<td>" . $fields[$k] . "</td>";
            }
            echo "</tr>";

            foreach ($dsatz as $key => $number) {
                //new table row for every record
                echo "Record <tr>";
                foreach ($number as $k => $content) {
                    //new table cell for every field of the record
                    echo "<td>" . $content . " </td>";
                }
            }

            echo "</table>";
        }

感谢您的时间。

1 个答案:

答案 0 :(得分:0)

试试这个:

        foreach ($dsatz as $key => $number) {

    // New code here -lighthart
            echo "insert into table ("
                 .implode(",", $fields)
                 .") values ("
                 .implode(",",$number).");"


            //new table row for every record
            foreach ($number as $k => $content) {
                //new table cell for every field of the record
                echo "<td>" . $content . " </td>";
            }
        }