Google Login with Google

Update Image in PHP (Replace Upload)

📌 Update Image in PHP (Replace Upload)

Uploading and deleting images is not enough.

👉 You also need to update (replace) an image

This means:

upload new image
delete old image
update database
1️⃣ Add edit button

Inside gallery.php:

<a href="edit.php?id=<?= $row['id'] ?>">Edit</a>
2️⃣ Create edit.php
/hosting/foliocraft/html/edit.php
3️⃣ Load existing data
<?php

require_once 'db.php';

$id = $_GET['id'];

$stmt = $conn->prepare("SELECT * FROM gallery WHERE id=?");
$stmt->bind_param("i", $id);
$stmt->execute();

$result = $stmt->get_result();
$row = $result->fetch_assoc();

?>
4️⃣ Create edit form
<form action="update.php" method="POST" enctype="multipart/form-data">

<input type="hidden" name="id" value="<?= $row['id'] ?>">

<p>Current Image:</p>
<img src="<?= $row['image_url'] ?>" width="200">

<input type="file" name="image">
<input type="text" name="title" value="<?= $row['title'] ?>">
<textarea name="caption"><?= $row['caption'] ?></textarea>

<button type="submit">Update</button>

</form>

👉 새 이미지는 선택 사항 (optional)

5️⃣ Create update.php
/hosting/foliocraft/html/update.php
6️⃣ Replace upload logic
<?php

require_once 'db.php';

$id = $_POST['id'];
$title = $_POST['title'];
$caption = $_POST['caption'];

$file = $_FILES['image'];

if ($file['name']) {

// 1. Get old image
$stmt = $conn->prepare("SELECT image_url FROM gallery WHERE id=?");
$stmt->bind_param("i", $id);
$stmt->execute();
$result = $stmt->get_result();
$row = $result->fetch_assoc();

$oldPath = $row['image_url'];

// 2. New file info
$ext = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
$allowed = ['jpg','jpeg','png','gif'];

if (!in_array($ext, $allowed)) {
die("Invalid file type.");
}

if ($file['size'] > 2 * 1024 * 1024) {
die("File too large.");
}

$newName = uniqid() . '.' . $ext;
$newPath = 'uploads/' . $newName;

// 3. Upload new file
if (move_uploaded_file($file['tmp_name'], $newPath)) {

// 4. Delete old file
if (file_exists($oldPath)) {
unlink($oldPath);
}

// 5. Update DB
$stmt = $conn->prepare("UPDATE gallery SET image_url=?, title=?, caption=? WHERE id=?");
$stmt->bind_param("sssi", $newPath, $title, $caption, $id);
$stmt->execute();

echo "Image updated.";

}

} else {

// Only update text
$stmt = $conn->prepare("UPDATE gallery SET title=?, caption=? WHERE id=?");
$stmt->bind_param("ssi", $title, $caption, $id);
$stmt->execute();

echo "Updated without changing image.";
}
?>
← Back to list
💬 Comments (0)