2

I'm having a problem importing .CSV data into a SQL database. I'm trying to use PDO in my PHP file to accomplish this and I can't seem to figure this out.

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';
}

Now this works, kind of. It imports the data but as you may have guessed this is only inserting the first row of the .CSV file, which by the way is the column headers. So I need to skip the first row and loop through the rest of this .CSV file.

Obviously throwing me some code would solve this, but more than that I would like an explanation of how to do this properly with PHP Data Objects (PDO). All the examples I've come across either have huge flaws or don't use PDO. Any and all help is welcomed and appreciated.

4

2 回答 2

3

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

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';
}

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

于 2013-08-20T19:24:00.423 回答
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";
于 2015-06-04T12:07:38.563 回答