查找并替换数据库中的所有修改脚本以返回受影响的行


find and replace all in database modify script to return affected rows

我在这里找到了这个非常酷的脚本:http://www.brilliantsheep.com/replacing-a-string-in-all-tables-of-a-database-in-mysql/

我已经尝试修改脚本,以便它使用:mysql_affected_rows() == 1显示受影响的行。这是测试UPDATE是否执行任何更新的正确方法吗?

<?php
    // Setup the associative array for replacing the old string with new string
    $replace_array = array(
        'test' => 'foo'
    );
    $mysql_link = mysql_connect( 'localhost', 'root', 'password' );
    if( ! $mysql_link) {
        die( 'Could not connect: ' . mysql_error() );
    }
    $mysql_db = mysql_select_db( 'database', $mysql_link );
    if(! $mysql_db ) {
        die( 'Can''t select database: ' . mysql_error() );
    }
    // Traverse all tables
    $tables_query = 'SHOW TABLES';
    $tables_result = mysql_query( $tables_query );
    $results = array();
    while( $tables_rows = mysql_fetch_row( $tables_result ) ) {
        foreach( $tables_rows as $table ) {
            // Traverse all columns
            $columns_query = 'SHOW COLUMNS FROM ' . $table;
            $columns_result = mysql_query( $columns_query );
            while( $columns_row = mysql_fetch_assoc( $columns_result ) ) {
                $column = $columns_row['Field'];
                $type = $columns_row['Type'];
                // Process only text-based columns
                if( strpos( $type, 'char' ) !== false || strpos( $type, 'text' ) !== false ) {
                    // Process all replacements for the specific column
                    foreach( $replace_array as $old_string => $new_string ) {
                        $replace_query = 'UPDATE ' . $table .
                            ' SET ' .  $column . ' = REPLACE(' . $column .
                            ', ''' . $old_string . ''', ''' . $new_string . ''')';
                        mysql_query( $replace_query );
                        if(mysql_affected_rows() == 1){
                            $results[] = $replace_query;
                        }
                    }
                }
            }
        }
    }
    mysql_free_result( $columns_result );
    mysql_free_result( $tables_result );
    mysql_close( $mysql_link );
    echo 'Rows affected!';
    echo '<ul>';
    foreach($results as $i){
        echo '<li>' . $i . '</li>';
    }
    echo '</ul>';
?>

mysql_affected_rows()将返回受影响的行数,因此您可能希望查找> 0而不是== 1。我会非常小心这个脚本,它几乎不可避免地会做一些你不想做的事情。

除了Tieran所说的,您还可以以更简单的方式进行UPDATE

$replace_query = 'UPDATE ' . $table .
                 ' SET ' .  $column . " = '$new_string'" ;