0

Is there a way to search in a database a custom string and replace it with a new one? The string I'm searching can appear in different tables and sometimes in different columns of the same table, so basically what i ned to do is search and replace everywhere.

2 Answers 2

1

You need a query like:

UPDATE [table_name] 
SET [field_name] = 
REPLACE([field_name],'[string_to_find]','[string_to_replace]');

Repeat for every relevant table and/or field in the database.

2
  • Thanks for your help but, is there a way to automate this for all tables in the database? and the fields... In my database the string i want to change can appear in different tables and in different fields of the same table.
    – Tales
    Mar 28, 2012 at 18:48
  • Probably not in SQL. You might need to script it in whatever flavor of scripting language (php, perl, shell, python, etc) you like. Mar 29, 2012 at 0:31
0

Here's a solution in PHP:

<?php

// edit this line to add old and new terms which you want to be replaced
$search_replace = array( 'old_term' => 'new_term', 'old_term2' => 'new_term2' );

//change the localhost,username,password and database-name according to your db
mysql_connect("localhost", "username", "password") or die(mysql_error());
mysql_select_db("database-name") or die(mysql_error());

$show_tables = mysql_query( 'SHOW TABLES' );
while( $st_rows = mysql_fetch_row( $show_tables ) ) {
    foreach( $st_rows as $cur_table ) {
        $show_columns = mysql_query( 'SHOW COLUMNS FROM ' . $cur_table );
        while( $cc_row = mysql_fetch_assoc( $show_columns ) ) {
            $column = $cc_row['Field'];
            $type = $cc_row['Type'];
            if( strpos( $type, 'char' ) !== false || strpos( $type, 'text' ) !== false ) {
                foreach( $search_replace as $old_string => $new_string ) {
                    $replace_query = 'UPDATE ' . $cur_table .
                        ' SET ' .  $column . ' = REPLACE(' . $column .
                        ', \'' . $old_string . '\', \'' . $new_string . '\')';
                    mysql_query( $replace_query );
                }
            }
        }
    }
}
echo 'replaced';
mysql_free_result( $show_columns );
mysql_free_result( $show_tables );
mysql_close( $mysql_link );

?>

Source

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.