ster ster - 2 months ago 6
MySQL Question

update values in table php-mysql

I have this table:

+----+------------+-----------------------+
| ID | ID_PRODUCT | LINK_DOWNLOAD |
+----+------------+-----------------------+
| 1 | 2369 | folder/2015.03.12.pdf |
| 2 | 3694 | folder/2014.01.10.pdf |
| 3 | 56 | folder/2016.09.25.pdf |
+----+------------+-----------------------+


End code php:

<form action="upload_file.php" method="post" enctype="multipart/form-data" name="upload_file"><br>
<label for="UploadFileField"></label><br>
<input type="file" name="UploadFileField"/>
<input type="submit" name="UploadButton" value="Upload" /><br>
<input type ="text" name="UPLOAD_COD" />
</form>


<?php
include "bd_cnx.php";
if (isset ($_FILES['UploadFileField'])){
$UploadName = $_FILES['UploadFileField'] ['name'];
$UploadName = mt_rand (100000, 999999).$UploadName;
$UploadTmp = $_FILES['UploadFileField'] ['tmp_name'];
$UploadType = $_FILES['UploadFileField'] ['type'];
$FileSize = $_FILES['UploadFileField'] ['size'];

$UploadName = preg_replace("#[^a-z0-9.]#i", "", $UploadName);

if(($FileSize > 1250000)){
die ("Error - File to big");
}

if(!$UploadTmp) {
die ("No File Selected");
}
else {
if (move_uploaded_file($UploadTmp, "Upload/$UploadName")) {
$UPLOAD_COD = $_POST['UPLOAD_COD'];
$sql = "INSERT INTO download (ID_PRODUCT,LINK_DOWNLOAD) VALUES ('$UPLOAD_COD','Upload/$UploadName')";
$result = $conn->query($sql);
echo '<script> alert("Successfully inserted"); window.location ="/index.php";</script>';
}
}
}
?>


2015.03.12.pdf file is today updating and becomes 2016.09.25.pdf . When i enter in the input "UPLOAD_COD" the number 2369, I want to delete the file 2015.03.12.pdf from server and be replaced with 2016.09.25.pdf, and in the LINK_DOWNLOAD column to be updated to the new link (folder/2015.03.12.pdf).
Thank you!

Answer

So you want to delete the file with ID_PRODUCT = 2369? just fetch it's LINK_DOWNLOAD from database

You put this code after uploading and inserting your file

//first create a query that select the row of the data that you are finding
$currentSql = "Select * from download where ID_PRODUCT = '".$UPLOAD_COD."'";
$current = $conn->query($currentSql);


// then fetch it's result then unlink the file from the server
while($row = $current->fetch_assoc()) {
    $file = $row['LINK_DOWNLOAD'];
    // check if file is exist then delete
    if (file_exists($file)) {
        unlink($file);
    }
}