我有这张桌子:
+----+------------+-----------------------+
| 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 |
+----+------------+-----------------------+
结束代码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文件今天更新,变成2016.09.25.pdf。当我输入输入&#34; UPLOAD_COD&#34;数字2369,我想从服务器删除文件2015.03.12.pdf并替换为2016.09.25.pdf,并在LINK_DOWNLOAD列中更新为新链接(文件夹/ 2015.03.12.pdf)。 谢谢!
答案 0 :(得分:1)
在执行插入查询后添加删除查询
$deleteSql = "Delete from download where ID_PRODUCT = '".$UPLOAD_COD."'";
$conn->query($deleteSql);
答案 1 :(得分:1)
您必须更新数据库中的相应条目:
UPDATE download SET LINK_DOWNLOAD='folder/2016.09.25.pdf' WHERE ID=1
我在WHERE
列上使用ID
条件,因为您没有告诉每个产品是否只有一个条目。如果每个产品只有一个条目,LINK_DOWNLOAD
也会在产品表中。
通过查看您的表,您可能有一个产品的多个下载链接,因为它似乎是一个链接表,所以如果您想要更新一个条目,可能您只想更新此条目。
因此,在您的代码中,我会添加一个块来查找UPLOAD_COD
中product_id输入的现有条目。
然后,如果您要更新指向物理文件的链接,则必须删除/存档初始文件。所以,你可以看看file_exists php命令,就像this SO question一样。
要完成,我只会在此产品有现有条目的情况下处理更新(也许您有其他标准,或者至少,如果需要,您可以稍后添加其他标准)。
希望这有帮助!
答案 2 :(得分:1)
所以你想删除ID_PRODUCT = 2369的文件?只需从数据库中获取LINK_DOWNLOAD
您在上传并插入文件后放置此代码
//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);
}
}