Last active
December 17, 2015 12:38
-
-
Save roine/5610714 to your computer and use it in GitHub Desktop.
Basic find and replace in all the tables from a secific database. I use this script for my wordpress deployment.
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 | |
/* | |
* find_and_replace_by takes 4 optional arguments | |
* first is the host | |
* second is db username | |
* third is db password | |
* fourth is database name | |
* ie: $ find_and_replace_by.php root password drupal | |
* or with two arguments: | |
* $ find_and_replace_by.php root drupal | |
* or no argument: | |
* $ find_and_replace_by.php | |
*/ | |
$host = "HOST"; | |
$database = "YOUR_DATABASE"; | |
$username = "YOUR_USERNAME"; | |
$password = "YOUR_PASSWORD"; | |
if($argc > 1 && $argc <= 5){ | |
$database = $argv[$argc-1]; | |
$host = $argv[1]; | |
$username = $argv[2]; | |
if($argc == 5){ | |
$password = $argv[3]; | |
} | |
else{ | |
$password = ''; | |
} | |
} | |
$find = "localhost"; | |
$replace_by = "liveserver.com"; | |
// Uncomment to swap find and replace_by values | |
// list($replace_by, $find) = array($find, $replace_by); | |
try{ | |
$connection = new PDO( "mysql:host={$host};dbname={$database}", $username, $password ); | |
} | |
catch(PDOException $e){ | |
die($e->getMessage()); | |
} | |
$tables = $connection->query("select * from information_schema.columns | |
where table_schema='{$database}' | |
order by table_name,ordinal_position"); | |
echo "Updating the rows.\n"; | |
$totalRows = $totalTables = $totalAffectedTables = $tempTotalRows = 0; | |
$currentTable = null; | |
while($result = $tables->fetch()){ | |
$table = $result[2]; | |
$column = $result[3]; | |
try{ | |
$query = $connection->query("UPDATE $table SET {$column} = replace($column, '{$find}', '{$replace_by}')"); | |
$totalRows += $query->rowCount(); | |
$tempTotalRows += $query->rowCount(); | |
if($currentTable != $table){ | |
$currentTable = $table; | |
$totalTables++; | |
$tempTotalRows = 0; | |
} | |
if($tempTotalRows == 1){ | |
$totalAffectedTables++; | |
} | |
} | |
catch(PDOException $e){ | |
die($e->getMessage()); | |
} | |
} | |
echo "Completed successfuly\n"; | |
echo plural($totalRows, 'row')." in ".plural($totalAffectedTables, 'table')." where affected\n"; | |
function plural($num, $str){ | |
if($num > 1){ | |
return "{$num} {$str}s"; | |
} | |
else{ | |
return "{$num} {$str}"; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment