插入CSV文件多行多数据

时间:2019-09-11 08:45:02

标签: php mysql

4202,4203
4204,4205,4207
4246,4247,4248,4249,4250
4815,4816,4817,4818,4819,4820
4824,4825,4826,4827,4828,4847,4848,4849
5143,5145,5146,5147,5148,5149

this is my csv file

逐行插入数据

insert into praking_location (Parking_meter_id) values (" csv file data")

我要插入500多个数据。

$open = fopen('meterid.csv','r'); 
while (!feof($open))  {

        $getTextLine = fgets($open);        
        $explodeLine = explode(",",$getTextLine);

        list($meter) = $explodeLine;

        $qry = "insert into praking_location (Parking_meter_id) 
         values('".$meter."')";
        mysqli_query($conn,$qry);
}
echo 'data inserted';

2 个答案:

答案 0 :(得分:0)

$open = fopen('meterid.csv','r'); 
while (!feof($open))  {

        $getTextLine = fgets($open);        
        $explodeLine = explode(",",$getTextLine);

        foreach($explodeLine as $meter) {
            $qry = "insert into praking_location (Parking_meter_id) 
             values('".$meter."')";
            mysqli_query($conn,$qry);
        }
}
echo 'data inserted';

答案 1 :(得分:0)

$open = fopen('meterid.csv','r'); 
while (!feof($open))  {
    $getTextLine = fgets($open);        
    $explodeLine = explode(",", $getTextLine);

    // Wrap every id for add
    $insertRows = array_map(function ($id) {
        return '("' . $id . '")';
    }, $explodeLine);

    // For add multiple rows
    $qry = "insert into praking_location (Parking_meter_id) values " . implode(',', $insertRows);
    mysqli_query($conn,$qry);
}

// Don't forget close file's handler
fclose($open);

echo 'data inserted';