fix_image_urls.php 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. <?php
  2. /**
  3. * Database migration script to fix incorrect image URLs in items table
  4. * This script will update all image URLs that contain incorrect paths
  5. */
  6. require_once 'backend/config/database.php';
  7. echo "Starting image URL migration...\n";
  8. try {
  9. $database = new Database();
  10. $db = $database->getConnection();
  11. echo "Connected to database successfully.\n";
  12. // First, let's see how many items have incorrect URLs
  13. $check_query = "SELECT id, picture FROM items WHERE picture LIKE '%/var/www/html/%' OR picture LIKE '%/api/%'";
  14. $check_stmt = $db->prepare($check_query);
  15. $check_stmt->execute();
  16. $incorrect_urls = $check_stmt->fetchAll(PDO::FETCH_ASSOC);
  17. $total_items = count($incorrect_urls);
  18. echo "Found {$total_items} items with incorrect image URLs.\n";
  19. if ($total_items === 0) {
  20. echo "No items need fixing. Migration complete.\n";
  21. exit(0);
  22. }
  23. // Update each incorrect URL
  24. $update_query = "UPDATE items SET picture = ? WHERE id = ?";
  25. $update_stmt = $db->prepare($update_query);
  26. $fixed_count = 0;
  27. foreach ($incorrect_urls as $item) {
  28. $old_url = $item['picture'];
  29. $new_url = $old_url;
  30. // Remove /var/www/html/ from the path
  31. if (strpos($new_url, '/var/www/html/') !== false) {
  32. $new_url = str_replace('/var/www/html/', '', $new_url);
  33. }
  34. // Remove /api/ from the beginning if present
  35. if (strpos($new_url, '/api/') !== false) {
  36. $new_url = str_replace('/api/', '', $new_url);
  37. }
  38. // Only update if the URL actually changed
  39. if ($new_url !== $old_url) {
  40. echo "Fixing item ID {$item['id']}: {$old_url} -> {$new_url}\n";
  41. $update_stmt->execute([$new_url, $item['id']]);
  42. $fixed_count++;
  43. }
  44. }
  45. echo "Successfully fixed {$fixed_count} image URLs.\n";
  46. echo "Migration completed successfully!\n";
  47. } catch (Exception $e) {
  48. echo "Error during migration: " . $e->getMessage() . "\n";
  49. exit(1);
  50. }
  51. ?>