Skip to content

Commit

Permalink
add a import_from_database_via_pdo sample
Browse files Browse the repository at this point in the history
  • Loading branch information
Mori Reo committed Dec 11, 2012
1 parent 003b1cb commit 8be967c
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 1 deletion.
29 changes: 29 additions & 0 deletions example/import_from_database_via_pdo.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
<?php

require_once __DIR__.'/../vendor/autoload.php'; // load composer

use Goodby\CSV\Import\Standard\Lexer;
use Goodby\CSV\Import\Standard\Interpreter;
use Goodby\CSV\Import\Standard\LexerConfig;

$pdo = new PDO('mysql:host=localhost;dbname=test', 'root', 'root');
$pdo->query('CREATE TABLE IF NOT EXISTS user (id INT, `name` VARCHAR(255), email VARCHAR(255))');

$config = new LexerConfig();
$lexer = new Lexer($config);

$interpreter = new Interpreter();

$interpreter->addObserver(function(array $columns) use ($pdo) {
$checkStmt = $pdo->prepare('SELECT count(*) FROM user WHERE id = ?');
$checkStmt->execute(array(($columns[0])));

$count = $checkStmt->fetchAll()[0][0];

if ($count === 0) {
$stmt = $pdo->prepare('INSERT INTO user (id, name, email) VALUES (?, ?, ?)');
$stmt->execute($columns);
}
});

$lexer->parse('user.csv', $interpreter);
2 changes: 1 addition & 1 deletion example/user.csv
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
1,alice,[email protected]
2,bob,[email protected]
3,carol,[email protected]
3,carol,[email protected]

0 comments on commit 8be967c

Please sign in to comment.