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

前端 未结 6 1740
深忆病人
深忆病人 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条回答
  •  情话喂你
    2020-12-30 12:58

    Well done on learning :)

    You should perhaps now learn about PDO in PHP, as it's (in my opinion) the best, safest and fastest way to execute MySQL queries in PHP:

    ' . PHP_EOL;
        $stmt = $db->prepare('UPDATE catalog_product_entity SET sku = :sku WHERE entity_id = :id');
        //Only give the length parameter if you **KNOW** that no line will be longer than that
        while (($data=fgetcsv($fin,1000,","))!==FALSE) {
            if ($stmt->execute(array(':sku' => $data[1], ':id' => $data[0]))) {
                echo 'Record updated 
    ' . PHP_EOL; } else { $err = $stmt->errorInfo(); echo 'Update Failed: ' . $err[2] . PHP_EOL; } } } catch (PDOException $e) { echo 'Connection failed: ' . $e->getMessage(); } fclose($fin);

    The PDO script has the following advantages over yours:

    • It's safer: PDO automatically quotes the data being inserted as needed. This prevents SQL injection attacks.
    • It's faster: PDO caches the query (in the prepare), and then uses the parameters passed in execute.
    • It's portable: PDO can connect to various types DB's, not just MySQL, so if you need to switchs DB's, its much easier.

提交回复
热议问题