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

标签 php mysql

我在这里发现了这个非常酷的脚本: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 。我会对这个脚本非常非常小心,它几乎不可避免地会做一些你不希望它做的事情。

关于php - 查找并替换数据库修改脚本中的所有内容以返回受影响的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12121656/

相关文章:

php - 检查 PDO 查询是否返回结果

mysql - 从多个表中删除数据

PHP SoapClient - 无法从外部实体加载 SOAP 错误 fatal error

php - 获取一个数字的 PHP 对象属性

php - dompdf - 当我指定 a4,横向时停止

php - 涉及mysql中两个表的搜索查询

php - mysql 服务器在 PDO 中消失了

sql - 多个外键有意义吗?

php - 链接并发送表单值到mysql数据库?

php - 从数据库收集统计数据