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

时间:2018-06-30 14:22:16

标签: php mysql csv

我有一个MS-excel文件,其列为:地址

还有一个MySQL数据库表,其列为:Add1,Add2,Add3

是否可以在Excel文件的地址列中断开数据并将其划分为Add1,Add2,Add3(每列限制为40个字符)通过PHP上传MSExcel文件之后!

我的代码用于在PHP中上传文件:

if(isset($_POST['submit'])) {
 if(isset($_FILES['uploadFile']['name']) && $_FILES['uploadFile']['name'] != "") {
    $allowedExtensions = array("xls","xlsx","csv");
    $ext = pathinfo($_FILES['uploadFile']['name'], PATHINFO_EXTENSION);
    if(in_array($ext, $allowedExtensions)) {
       $file_size = $_FILES['uploadFile']['size'] / 1024;
       if($file_size < 50) {
           $file = "../excelfile/".$_FILES['uploadFile']['name'];
           $isUploaded = copy($_FILES['uploadFile']['tmp_name'], $file);
           if($isUploaded) {

                include("../Classes/PHPExcel/IOFactory.php");
                try {
                    //Load the excel(.xls/.xlsx/.csv) file
                    $objPHPExcel = PHPExcel_IOFactory::load($file);
                } catch (Exception $e) {
                     die('Error loading file "' . pathinfo($file, PATHINFO_BASENAME). '": ' . $e->getMessage());
                }

                //An excel file may contains many sheets, so you have to specify which one you need to read or work with.
                $sheet = $objPHPExcel->getSheet(0);
                //It returns the highest number of rows
                $total_rows = $sheet->getHighestRow();
                //It returns the highest number of columns
                $total_columns = $sheet->getHighestColumn();
                $sheet_data = $objPHPExcel->getActiveSheet()->toArray(null,true,true,true);

将地址插入表中的查询为:

$query = "insert into address_table (Add1, Add2, Add3)
    values(
    '".$_POST['address1']."',
    '".$_POST['address2']."',
    '".$_POST['address3']."')

1 个答案:

答案 0 :(得分:1)

由于我没有您的Excel文件,我需要做一些估算。

想象一下您的$sheet_data现在看起来像这样

Array
(
    [0] => Array
        (
            [0] => Street1
        )

    [1] => Array
        (
            [0] => Street2
        )

    [2] => Array
        (
            [0] => Street3 with a long name, more than 40 characters
        )

)

第一层的每个Array-Element代表一行,第二层的每个元素都包含相应的列。

foreach ($sheet_data as $line){
    //maybe you need to skip the first line because it could contain just some headers
    //in my estimation $line[0] contains the address
    $address = $line[0];

    //split address after 40 characters
    $split = str_split($address, 40);

    //$conn - mysqli connection
    $stmt = $conn->prepare("INSERT INTO address_table (Add1, Add2, Add3)
    VALUES (?, ?, ?)");

    $addr1=""; $addr2=""; $addr3="";
    if(isset($split[0]) $addr1 = $split[0];
    if(isset($split[1]) $addr2 = $split[1];
    if(isset($split[2]) $addr3 = $split[2];

    //fill query params params with values
    $stmt->bind_param("sss", $addr1, $addr2, $addr3);

    $stmt->execute();
}

对于第三行-表条目将填充

Add1 => Street3 with a long name, more than 40 c
Add2 => haracters   

您仍然需要检查一件事-如果地址的字符数超过120个,则其他字符会丢失atm。

请像我的示例一样使用准备好的语句-当您用变量直接填充查询时,您容易受到SQL-Injection

的攻击