Advertisement
Guest User

Untitled

a guest
Nov 6th, 2016
122
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.05 KB | None | 0 0
  1. <?php
  2.  
  3. // A way to globally replace strings in a MySQL database, particularly useful for changing the name
  4. // of a host when moving a WordPress installation from one server to another. This script also auto
  5. // detects any serialized PHP objects, unserializes them, replaces the string and then saves the
  6. // reserialized object.
  7.  
  8. if (sizeof($argv) !== 7) {
  9. die("usage: php mysql-replace-string.php host db-name username password old-string new-string\n");
  10. }
  11.  
  12. $host = $argv[1];
  13. $dbName = $argv[2];
  14. $username = $argv[3];
  15. $password = $argv[4];
  16. $oldStr = $argv[5];
  17. $newStr = $argv[6];
  18.  
  19. $db = new PDO("mysql:host=$host;dbname=$dbName;charset=utf8mb4", $username, $password, array(
  20. PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
  21. ));
  22.  
  23. function replaceNestedStrings(&$obj, $pattern, $replacement) {
  24. if (is_array($obj)) {
  25. foreach ($obj as &$item) {
  26. replaceNestedStrings($item, $pattern, $replacement);
  27. }
  28. } else if (is_string($obj)) {
  29. $obj = str_replace($pattern, $replacement, $obj);
  30. }
  31. }
  32.  
  33. foreach ($db->query('SHOW TABLES') as $tables) {
  34.  
  35. foreach ($db->query("SELECT * FROM {$tables[0]}") as $row) {
  36.  
  37. $updates = [];
  38. $where = [];
  39. $newValues = [];
  40. $oldValues = [];
  41.  
  42. foreach ($row as $n=>$column) {
  43. if (!is_int($n)) {
  44.  
  45. $oldValues[] = $row[$n];
  46.  
  47. // echo "$n=>$column\n";
  48. $data = @unserialize($column);
  49. if ($data !== false) { // is a serialized obj?
  50. replaceNestedStrings($data, $oldStr, $newStr);
  51. $row[$n] = serialize($data);
  52. } else {
  53. replaceNestedStrings($row[$n], $oldStr, $newStr);
  54. }
  55.  
  56. // Use $n to prefix so that merge below doesn't overwrite
  57. $newValues[$n] = $row[$n];
  58.  
  59. $updates[] = "$n=?";
  60. $where[] = "$n=?";
  61. }
  62. }
  63.  
  64. $updatesStr = implode(',', $updates);
  65. $whereStr = implode(' AND ', $where);
  66.  
  67. $sql = "UPDATE {$tables[0]} SET {$updatesStr} WHERE {$whereStr}";
  68.  
  69. $stmt = $db->prepare($sql);
  70.  
  71. // Need to use array_values as PDO expects numeric indexes
  72. $stmt->execute(array_values($newValues + $oldValues));
  73.  
  74. }
  75.  
  76. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement