Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trial
nicholas maddren
12,793 PointsHow can I add this to my code?
Here is my code:
<?php $databasehost = "localhost"; $databasename = "import"; $databasetable = "import"; $databaseusername="username"; $databasepassword = "password"; $fieldseparator = ","; $lineseparator = "\n"; $csvfile = "test.csv";
if(!file_exists($csvfile)) { die("File not found. Make sure you specified the correct path."); }
try { $pdo = new PDO("mysql:host=$databasehost;dbname=$databasename", $databaseusername, $databasepassword, array( PDO::MYSQL_ATTR_LOCAL_INFILE => true, PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION ) ); } catch (PDOException $e) { die("database connection failed: ".$e->getMessage()); }
$affectedRows = $pdo->exec("
LOAD DATA LOCAL INFILE ".$pdo->quote($csvfile)." INTO TABLE $databasetable
FIELDS TERMINATED BY ".$pdo->quote($fieldseparator)."
LINES TERMINATED BY ".$pdo->quote($lineseparator));
echo "Loaded a total of $affectedRows records from this csv file.\n";
?>
When I replace the LOAD DATA LOCAL INFILE command with the REPLACE command I get an error which makes me believe I am doing something wrong haha, I just need the script to replace the current database table with the CSV file instead of adding to the database, where do I add the REPLACE syntax? Thanks :)
1 Answer
Iain Simmons
Treehouse Moderator 32,305 PointsAccording to the MYSQL documentation for LOAD DATA INFILE (http://dev.mysql.com/doc/refman/5.1/en/load-data.html) the 'REPLACE' keyword comes between the filename and 'INTO TABLE'.
So your $affectedRows would be the following:
$affectedRows = $pdo->exec(" LOAD DATA LOCAL INFILE ".$pdo->quote($csvfile)." REPLACE INTO TABLE $databasetable FIELDS TERMINATED BY ".$pdo->quote($fieldseparator)." LINES TERMINATED BY ".$pdo->quote($lineseparator));