Change Image Filenames In MYSQL (jpg to png)

Create a script (replacing the variables as necessary) and run it to replace ALL instances of (in this case) “star.jpg” to “star.png”


<?php

// CHANGE THESE VARIABLES TO MATCH YOUR SERVER SETTINGS
$DB_Host = 'localhost';
$DB_Name = 'Your_Database_Name';
$DB_User = 'Database_User_Name';
$DB_Password = 'Your_Database_Password';

// What Do You Want To Change?

$OldValue = 'star.jpg';
$NewValue = 'star.png';

// ** DONE EDITING ** //

// Connect to your WordPress database
$conn = mysqli_connect($DB_Host, $DB_User, $DB_Password, $DB_Name);

// Check connection
if (!$conn) {
  die("Connection failed: " . mysqli_connect_error());
}

// Escape the image filenames for safe SQL query usage
$old_image = mysqli_real_escape_string($conn, $OldValue);
$new_image = mysqli_real_escape_string($conn, $NewValue);

// Construct the update query
$sql = "UPDATE `your_table_name` SET `post_content` = REPLACE(`post_content`, '$old_image', '$new_image')";

// Execute the query
if (mysqli_query($conn, $sql)) {
  echo "Image URL updated successfully.";
} else {
  echo "Error updating image URL: " . mysqli_error($conn);
}

// Close the connection
mysqli_close($conn);

?>
Disclaimer: The code on this website is provided "as is" and comes with no warranty. The author of this website does not accept any responsibility for issues arising from the use of code on this website. Before making any significant changes, ensure you take a backup of all files and do not work directly on a live/production website without thoughly testing your changes first.

Leave a Reply

Your email address will not be published. Required fields are marked *