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.