Writing a PHP file to read from CSV and execute SQL Query

前端 未结 6 1749
深忆病人
深忆病人 2020-12-30 12:39

I would like a PHP script to read the contents from a CSV file in the following format

id, sku
1,104101
2,105213

there are a total of 1486

6条回答
  •  猫巷女王i
    2020-12-30 13:05

    You will need to do something like:

    $filename = "file_name_on_server.csv"
    $fp = fopen( $filename ,"r");
    while ($line = fgets ($fp))
    {
    

    now use Split to get an array of the comma delimited values

        $arr = split (",", $line);
    

    Now you have an array for the comma delimited values on $line. You can do simple string formatting to stick those values into an SQL query.

        $query = "INSERT INTO `TableBlah` (Field1, Field2) VALUES (" . $arr[0] . "," . $arr[1] . ")";
    

    Use the mysql api to send those queries to the database

    }
    fclose($fp);
    

提交回复
热议问题