使用PDO导入带有PHP的.CSV文件

时间:2013-08-20 18:44:18

标签: php pdo

我在将.CSV数据导入SQL数据库时遇到问题。我正在尝试在我的PDO文件中使用PHP来完成此操作,而我似乎无法弄清楚这一点。

if (isset($_FILES['uploadedfile'])) {   

    // get the csv file and open it up
    $file = $_FILES['uploadedfile']['tmp_name']; 
    $handle = fopen($file, "r"); 
    try { 
        // prepare for insertion
        $query_ip = $db->prepare('
                INSERT INTO projects (                                      
                    id, project_name, contact, pm, apm, 
                    est_start, est_end, trips, tasks, perc_complete, 
                    bcwp, actual, cpi, bcws, bac, 
                    comments, status, project_revenue, profit_margin, pm_perc, 
                    audited, account_id
                ) VALUES (
                    ?, ?, ?, ?, ?,
                    ?, ?, ?, ?, ?, 
                    ?, ?, ?, ?, ?,
                    ?, ?, ?, ?, ?, 
                    ?, ?            
                )');                                         
        $data = fgetcsv($handle,1000,",","'");
        $query_ip->execute($data);
        $count = $query_ip->rowCount(); 
        fclose($handle);

    } catch(PDOException $e) {
        die($e->getMessage());
    }       

    echo 'Projects imported ' . $count . ' rows were affected';

} else {
    echo 'Could not import projects';
}

现在这个有效,有点。它会导入数据,但您可能已经猜到这只是插入.CSV文件的第一行,顺便说一下是列标题。所以我需要跳过第一行并循环遍历此.CSV文件的其余部分。

显然给我一些代码可以解决这个问题,但不止于此我想解释如何使用PHP Data Objects (PDO)正确地解决这个问题。我遇到的所有例子都有很大的缺陷或者没有使用PDO。任何和所有帮助都受到欢迎和赞赏。

2 个答案:

答案 0 :(得分:1)

评论帮我提出了这个答案。我使用了以下代码

if (isset($_FILES['uploadedfile'])) {   

    // get the csv file and open it up
    $file = $_FILES['uploadedfile']['tmp_name']; 
    $handle = fopen($file, "r"); 
    try { 
        // prepare for insertion
        $query_ip = $db->prepare('
            INSERT INTO projects (                                      
                id, project_name, contact, pm, apm, 
                est_start, est_end, trips, tasks, perc_complete, 
                bcwp, actual, cpi, bcws, bac, 
                comments, status, project_revenue, profit_margin, pm_perc, 
                audited
            ) VALUES (
                ?, ?, ?, ?, ?,
                ?, ?, ?, ?, ?, 
                ?, ?, ?, ?, ?,
                ?, ?, ?, ?, ?, 
                ?           
            )
        ');

        // unset the first line like this       
        fgets($handle);

        // created loop here
        while (($data = fgetcsv($handle, 1000, ',')) !== FALSE) {
            $query_ip->execute($data);
        }       

        fclose($handle);

    } catch(PDOException $e) {
        die($e->getMessage());
    }

    echo 'Projects imported';

} else {
    echo 'Could not import projects';
}

我希望这可以帮助未来的读者使用PDO正确导入他们的.CSV文件。应该注意,这应该在实时服务器/站点上使用。此代码具有针对可能有害上传的0保护。

答案 1 :(得分:1)

error_reporting(E_ALL);
ini_set('display_errors', 1);

/* Database connections */
$_host = 'localhost';
$_name = 'root';
$_password = 'root';
$_database = 'TEST';

/* ========= Variables =========== */

/**
 * Defines the name of the table where data is to be inserted
 */
$table = 'terms';

/**
 * Defines the name of the csv file which contains the data
 */
$file = 'terms.csv';

/* =========== PDO ================= */
try {
$link = new PDO('mysql:dbname=' . $_database . ';host=' . $_host . ';charset=utf8', $_name, $_password, array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));
    $link->exec("set names utf8");
} catch (PDOException $ex) {
    die(json_encode(array('outcome' => false, 'message' => 'Unable to connect')));
}
$link->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);

/* ========= Load file content in an array ========== */
$rows = array_map('str_getcsv', file($file));
$header = array_shift($rows);
$csv = array();
foreach ($rows as $row) {
    $csv[] = array_combine($header, $row);
}

/* ========= Insert Script ========== */
foreach ($csv as $i => $row) {
    insert($row, $table);
}

function insert($row, $table) {
    global $link;
    $sqlStr = "INSERT INTO $table SET ";
    $data = array();
    foreach ($row as $key => $value) {
        $sqlStr .= $key . ' = :' . $key . ', ';
        $data[':' . $key] = $value;
    }
    $sql = rtrim($sqlStr, ', ');
    $query = $link->prepare($sql);
    $query->execute($data);
}

echo "Done inserting data in $table table";