我在这里找到了这个非常酷的脚本: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>';
?>