0

I have an input field as image and here how I am updating it in the database with php:

if (isset($_POST['benefit_update'])) {
    $benefit_id = $_POST['benefit_id'];

    $old_filename = $_POST['old_image'];
    $image = $_FILES['image']['name'];
    $update_filename = $image;

    if (!empty($old_filename)) {
        if (file_exists('../uploads/benefits/' . $old_filename)) {
            unlink("../uploads/benefits/" . $old_filename);
        }
    }

    if (!empty($image)) {
        move_uploaded_file($_FILES['image']['tmp_name'], '../uploads/benefits/' . $update_filename);
    } else {
        $update_filename = "";
    }

    $status = $_POST['status'] == true ? '1' : '0';

    $query = "UPDATE benefits SET 
    image='$update_filename', status='$status'
        WHERE id='$benefit_id'";

    $query_run = mysqli_query($con, $query);
}

with this code when I try to edit the file, the file is not selected. and if I dont select again the same file, the column updates empty. I am newbie in php and I wonder how to fix it?

Barmar
  • 741,623
  • 53
  • 500
  • 612
  • 4
    Your script is vulnerable to [SQL Injection Attack](https://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php). Even if [you are escaping variables, its not safe](https://stackoverflow.com/questions/5741187/sql-injection-that-gets-around-mysql-real-escape-string%5D)! You should always use [prepared statements and parameterized queries](https://www.php.net/manual/en/mysqli.quickstart.prepared-statements.php) in either MYSQLI or PDO instead of concatenating variables into the query. – Barmar Jul 03 '23 at 21:23
  • 1
    Please add the result of `var_dump($_POST);` to the question. – Barmar Jul 03 '23 at 21:25

0 Answers0