Peter Sondak
Peter Sondak

Reputation: 45

PHP / MySQL: Rename $_FILES['image']['name'] base on id

can anyone help me to solve my problem? Currently, I created a system that can upload a photo and the function successful. but the name of the photo that saves to the database and also at the server folder is the actual name of the photo.

Now, I want to rename the photo based on id. Below is my code:

<?php

    require_once '../../../../config/configPDO.php';

    $report_id = $_POST['report_id'];

    $image = $_FILES['uploadFile']['name'];

    // image file directory
    $target = "../../../../images/upload/".basename($image);
    $ServerURL = "http://172.20.0.45/tgotworker_testing/images/upload/$image";

      // Prepare an insert statement
        $query = "UPDATE ot_report SET photo_before = '$ServerURL', time_photo_before = GETDATE() WHERE report_id = :report_id";
        $sql = $conn->prepare($query);
        $sql->bindParam(':report_id', $report_id);
        $sql->execute();


          // Attempt to execute the prepared statement
          if($sql&&move_uploaded_file($_FILES['uploadFile']['tmp_name'], $target)){
              // Records created successfully. Redirect to landing page
            echo "<script>alert('Saved')</script>";
            header("Location: view_task.php?report_id=".$_POST['report_id']);

              exit();
          } else{
              echo "Something went wrong. Please try again later.";
          }

?>

Upvotes: 0

Views: 273

Answers (2)

kozulov
kozulov

Reputation: 77

Change one line of your code

$target = "../../../../images/upload/".$report_id . '.'. pathinfo($image, PATHINFO_EXTENSION);

Upvotes: 1

Tushar
Tushar

Reputation: 568

Try this code

require_once '../../../../config/configPDO.php';

$report_id = $_POST['report_id'];
$image = $_FILES['uploadFile']['name'];

//set new name for upload image
$temp = explode(".", $_FILES["file"]["name"]);
$newfilename = $report_id. '.' . end($temp);

$target = "../../../../images/upload/".$newfilename;
$ServerURL = "http://172.20.0.45/tgotworker_testing/images/upload/$newfilename";

// Prepare an insert statement
$query = "UPDATE ot_report SET photo_before = '$ServerURL', time_photo_before = GETDATE() WHERE report_id = :report_id";
$sql = $conn->prepare($query);
$sql->bindParam(':report_id', $report_id);
$sql->execute();


// Attempt to execute the prepared statement
if($sql&&move_uploaded_file($_FILES['uploadFile']['tmp_name'], $target)){
     // Records created successfully. Redirect to landing page
     echo "<script>alert('Saved')</script>";
     header("Location: view_task.php?report_id=".$_POST['report_id']);
      exit();
} else{
          echo "Something went wrong. Please try again later.";
}

?>

Upvotes: 1

Related Questions