Created
January 3, 2017 14:42
-
-
Save tarjei/0d57eb7b3118592b411558107f816a6d to your computer and use it in GitHub Desktop.
Fix spaces in mysql rows
This file contains hidden or 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 | |
$host = '127.0.0.1'; | |
$db = 'dbname'; | |
$user = 'username'; | |
$pass = 'password'; | |
$charset = 'utf8'; | |
$dsn = "mysql:host=$host;dbname=$db;charset=$charset"; | |
$opt = [ | |
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, | |
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC, | |
PDO::ATTR_EMULATE_PREPARES => false, | |
]; | |
$pdo = new PDO($dsn, $user, $pass, $opt); | |
$stmt = $pdo->query("SELECT id, username, username_canonical, email, email_canonical | |
FROM User WHERE username LIKE '% %'"); | |
$updStatement = $pdo->prepare( | |
"UPDATE User set username=?, username_canonical =?, email = ?, email_canonical = ? WHERE id=?"); | |
foreach ($stmt as $row) | |
{ | |
foreach($row as $key => $v) { | |
if ($key ==='id') { | |
continue; | |
} | |
$n = mb_substr($v, -1, 1, 'utf-8'); | |
$r = preg_replace('/(^\s+)|(\s+$)/u', "", $v); | |
printf("%s UPD: '%s' -> '%s' %s %d\n", $key, $v, $r, $n, ord($n)); | |
$row[$key] = $r; | |
} | |
$updStatement->execute([ | |
$row['username'], | |
$row['username_canonical'], | |
$row['email'], | |
$row['email_canonical'], | |
$row['id'] | |
]); | |
print $updStatement->rowCount() . " rows updated\n"; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment