Skip to content

Instantly share code, notes, and snippets.

@visitdigital
Last active July 23, 2021 09:41
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save visitdigital/9544808 to your computer and use it in GitHub Desktop.
Save visitdigital/9544808 to your computer and use it in GitHub Desktop.
Mass Find and Replace MySQL
<?php
/*
* MySQL Mass Find and Replace
* Author: Lee Woodman - https://www.linkedin.com/in/leewoodman
* License: GNU
*/
// Connect to your MySQL database.
$hostname = "localhost";
$username = "root";
$password = "password";
$database = "db_name";
mysql_connect($hostname, $username, $password);
// The find and replace strings.
$find = "what_i_need_to_find";
$replace = "what_i_need_to_replace_with";
// Test mode
$test_mode = false;
// Loop through all tables and columns
$loop = mysql_query("
SELECT
concat('UPDATE ',table_schema,'.',table_name, ' SET ',column_name, '=replace(',column_name,', ''{$find}'', ''{$replace}'');') AS s
FROM
information_schema.columns
WHERE
table_schema = '{$database}'")
or die ('Cannot loop through database fields: ' . mysql_error());
while ($query = mysql_fetch_assoc($loop))
{
if ($test_mode)
echo "{$query['s']}<br/>";
else
mysql_query($query['s']);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment