0

上传 csv 文件后生成密钥 ID 有问题,这是我的代码:

if (isset($_FILES['userfile'])) {
    $csv_file = $_FILES['userfile']['tmp_name'];
    $csv_count = count(file($_FILES['userfile']['tmp_name']));
    if (!is_file($csv_file))
        exit('File not found.');
    if (($handle = fopen($csv_file, "r")) !== FALSE) {
        while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
            for ($i = 1; $i <= $csv_count; $i++) {
                if (strlen($i) == 1) {
                    $i = "0000000" . $i;
                } elseif (strlen($i) == 2) {
                    $i = "000000" . $i;
                } elseif (strlen($i) == 3) {
                    $i = "00000" . $i;
                } elseif (strlen($i) == 4) {
                    $i = "0000" . $i;
                } elseif (strlen($i) == 5) {
                    $i = "000" . $i;
                } elseif (strlen($i) == 6) {
                    $i = "00" . $i;
                } elseif (strlen($i) == 7) {
                    $i = "0" . $i;
                } else {
                    $i = $i;
                }
                $key_id = "BRK" . substr(date('y'), -2) . "5" . $i;
                $qry = mysql_query("INSERT INTO table                    VALUES('$key_id','$data[1]','$data[2]','$data[3]','$data[4]','$data[5]','$data[6]','$data[7]','$data[8]','$data[9]','$data[10]','$data[11]','$data[12]','$data[13]','$data[14]','$data[15]','$data[16]','$data[17]','$data[18]','$data[19]','$data[20]','$data[21]','$data[22]','$data[23]','$data[24]','$data[25]','$data[26]','$data[27]','$data[28]','$data[29]','$data[30]','$data[31]','$data[32]','$data[33]','$data[34]','$data[35]')");
            }
        }
        fclose($handle);
    }
}

当我插入查询时可以,但结果不可以。

结果 key_id 是好的(按我的意愿生成),但其他字段,每一行都与第一行有相同的数据。

请帮忙,谢谢提前。

4

1 回答 1

1

您按函数读取所有文件file,底部再次读取并按文件中的每一行插入 DB N 记录。尝试这个。

if (isset($_FILES['userfile'])) {
    $csv_file = $_FILES['userfile']['tmp_name'];
    if (!is_file($csv_file))
        exit('File not found.');
    if (($handle = fopen($csv_file, "r")) !== FALSE) {
       $i = 1;
       while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
            $key = str_pad($i, 8, '0', STR_PAD_LEFT);

            $key_id = "BRK" . substr(date('y'), -2) . "5" . $key;
            $qry = mysql_query("INSERT INTO table                    VALUES('$key_id','$data[1]','$data[2]','$data[3]','$data[4]','$data[5]','$data[6]','$data[7]','$data[8]','$data[9]','$data[10]','$data[11]','$data[12]','$data[13]','$data[14]','$data[15]','$data[16]','$data[17]','$data[18]','$data[19]','$data[20]','$data[21]','$data[22]','$data[23]','$data[24]','$data[25]','$data[26]','$data[27]','$data[28]','$data[29]','$data[30]','$data[31]','$data[32]','$data[33]','$data[34]','$data[35]')");

            $i++;
        }
    }
    fclose($handle);
}

}

于 2013-11-13T06:46:27.843 回答