Skip to content

Instantly share code, notes, and snippets.

@pkdavies
Created June 6, 2023 16:31
Show Gist options
  • Save pkdavies/8ccb77b0155f13b11bf55e08669b2bc4 to your computer and use it in GitHub Desktop.
Save pkdavies/8ccb77b0155f13b11bf55e08669b2bc4 to your computer and use it in GitHub Desktop.
Find and replace script
<?php
// Your search word goes here
$search_word = 'https://url.to.find/';
$replacement_word = 'https://cdn.new.com/';
// Set your database credentials
$servername = 'mysql.database.azure.com';
$database = "prod";
$username = "user";
$password = "pa$$";
// Connect to the database
$conn = mysqli_connect($servername, $username, $password, $database);
if (!$conn) {
die('Error connecting to the database: ' . mysqli_connect_error());
}
// Fetch all table names in the database
$tables = [];
$tables_result = mysqli_query($conn, 'SHOW TABLES');
while ($row = mysqli_fetch_row($tables_result)) {
$tables[] = $row[0];
}
// Iterate through each table and search for the word
foreach ($tables as $table) {
// Get column names for the table
$columns = [];
$columns_result = mysqli_query($conn, "SHOW COLUMNS FROM $table");
while ($column_row = mysqli_fetch_assoc($columns_result)) {
$columns[] = $column_row['Field'];
}
// Construct a SELECT query with LIKE conditions for each column
$where_conditions = [];
foreach ($columns as $column) {
$where_conditions[] = "$column LIKE '%$search_word%'";
}
$where_clause = implode(' OR ', $where_conditions);
$query = "SELECT * FROM $table WHERE $where_clause";
// Execute the query and process the results
$results = mysqli_query($conn, $query);
if (mysqli_num_rows($results) > 0) {
echo "Updating records in table: $table\n";
echo "------------------------------------\n";
// Iterate through the rows and perform the replacement
while ($row = mysqli_fetch_assoc($results)) {
// Update each column in the row
foreach ($columns as $column) {
$original_value = $row[$column];
$updated_value = str_replace($search_word, $replacement_word, $original_value);
// Update the column if the value has changed
if ($original_value !== $updated_value) {
$escaped_updated_value = mysqli_real_escape_string($conn, $updated_value);
$update_query = "UPDATE $table SET $column = '$escaped_updated_value' WHERE {$column} = '{$original_value}'";
if (mysqli_query($conn, $update_query)) {
echo "Updated row in column '$column': '$original_value' -> '$updated_value'\n";
} else {
echo "Error updating row: " . mysqli_error($conn) . "\n";
}
}
}
}
echo "\n";
}
}
// Close the database connection
mysqli_close($conn);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment