Created
May 11, 2014 07:01
-
-
Save Daniel15/0e4416ab552115a87a95 to your computer and use it in GitHub Desktop.
Fixing badly-encoded UTF-8 characters in MySQL database
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// Go home PHP, you're drunk. | |
// No charset here | |
$old_db = new PDO('mysql:host=localhost;dbname=database', 'username', 'password'); | |
$old_db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); | |
// Charset here | |
$new_db = new PDO('mysql:charset=utf8mb4;host=localhost;dbname=database2', 'username', 'password'); | |
$new_db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); | |
$result = $old_db->query('SELECT * FROM items'); | |
$row = $result->fetch(PDO::FETCH_ASSOC); | |
$columns = array_keys($row); | |
// [foo, bar] => [':foo', ':bar'] for query params | |
$placeholders = array_map(function($column) { return ':' . $column; }, $columns); | |
// INSERT INTO items (foo, bar) VALUES (:foo, :bar) | |
$insert = $new_db->prepare('INSERT INTO items (' . implode(', ', $columns) . ') VALUES (' . implode(', ', $placeholders) . ')'); | |
do { | |
$insert->execute($row); | |
echo '.'; | |
} while ($row = $result->fetch(PDO::FETCH_ASSOC)); | |
echo "\nDone"; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment