将XLSX工作表插入数据库

时间:2018-11-06 11:27:06

标签: php database wordpress foreach xlsx

我想将XLSX文件的内容插入数据库。该文件使用simple-xlsx解析器(https://www.phpclasses.org/package/6279-PHP-Parse-and-retrieve-data-from-Excel-XLS-files.html)进行了很好的解析。

关于工作表和列,我具有以下结构。

系列 序列号,零件号

文件 零件号,手册,BOM,TUV

所以在我的数据库中,我将有以下几列:

ID,序列号,零件号,手册,物料清单,tuv

我在序列表中有约88k行,在文件表中有约1.5k行。序列号是唯一的编号,但是零件号可以属于更多的序列号,这是迷路的步骤。

示例:

serial 1, partnumber 10, manual 10.pdf, bom 10.pdf, tuv 10.pdf
serial 2, partnumber 10, manual 10.pdf, bom 10.pdf, tuv 10.pdf
serial 3, partnumber 10, manual 10.pdf, bom 10.pdf, tuv 10.pdf
serial 4, partnumber 11, manual 11.pdf, bom 11.pdf, tuv 11.pdf
serial 5, partnumber 11, manual 11.pdf, bom 11.pdf, tuv 11.pdf

当前代码,我认为这完全是一团糟,我迷路了……

public function prepare_xlsx_to_db( $serials, $files, $break ) {

        global $wpdb;
        $response = array();
        $insert_string = array();
        $temp_string = array();
        $current_block = 0;
        $total_serials = count( $serials );
        $wp_table_name = $wpdb->prefix . 'ga_serials';

        foreach ( $serials as $key => $serial ) {

            if ( $key === 0 ) continue; // Skipping the first row.

            $temp_string[$key] = array(
                'serial'        => $serial[0],
                'partnumber'    => $files[array_search($serial[1],array_column($files,0),true)][0],
                'manual'        => $files[array_search($serial[1],array_column($files,0),true)][1],
                'bom'           => $files[array_search($serial[1],array_column($files,0),true)][2],
                'tuv'           => $files[array_search($serial[1],array_column($files,0),true)][3]
            );
        }

        foreach ( $temp_string as $key => $row ) {

            if ( $key === 0 ) continue; // Skipping the first row.

            $insert_string[] = $wpdb->prepare( "(%s,%s,%s,%s,%s)", $row['serial'], $row['partnumber'], $row['manual'], $row['bom'], $row['tuv'] );

            if ( $current_block == $break || $key == $total_serials - 1  ) {
                $query = "INSERT INTO {$wp_table_name} (serial, partnumber, manual, bom, tuv) VALUES ";
                $query .= implode( ",\n", $insert_string );
                if ( $wpdb->query( $wpdb->prepare( $query, $insert_string ) ) ) {
                    $response[ 'success' ] = 'true';
                    $response[ 'msg' ] = "File imported succesfully into the database.";
                } else {
                    $response[ 'success' ] = 'false';
                    $response[ 'msg' ] = 'bla';
                }
                $current_block = 0;
                unset( $insert_string );
            } else {
                $current_block++;
            }
        }

        return json_encode( $response );
    }

在数据库中,我发现了被覆盖的行。我在做什么错了?

0 个答案:

没有答案