我有一个文件可能会移动到2个位置,具体取决于用户在单独页面上单击的按钮:
目前我已声明该文件是否进入“ImageFiles”文件夹,然后移动文件夹并插入数据库行。
但我还要包括如果文件尚未上传到'ImageFiles'文件夹,则使用以下代码删除数据库行:
$imagecancelsql = "DELETE FROM Image
WHERE ImageFile = 'ImageFiles/".
mysql_real_escape_string($_FILES['fileImage']['name'])."'";
mysql_query($imagecancelsql);
这可能吗?如果可以的话,如何在php脚本中的当前if / else语句中编写?
下面是php脚本:
<?php
session_start();
...//connect to DB
$result = 0;
if( is_file("ImageFiles/".$_FILES['fileImage']['name'])) {
$parts = explode(".",$_FILES['fileImage']['name']);
$ext = array_pop($parts);
$base = implode(".",$parts);
$n = 2;
while( is_file("ImageFiles/".$base."_".$n.".".$ext)) $n++;
$_FILES['fileImage']['name'] = $base."_".$n.".".$ext;
move_uploaded_file($_FILES["fileImage"]["tmp_name"],
"ImageFiles/" . $_FILES["fileImage"]["name"]);
$result = 1;
$imagesql = "INSERT INTO Image (ImageFile)
VALUES ('ImageFiles/".mysql_real_escape_string($_FILES['fileImage']['name'])."')";
mysql_query($imagesql);
}
else
{
move_uploaded_file($_FILES["fileImage"]["tmp_name"],
"ImageFiles/" . $_FILES["fileImage"]["name"]);
$result = 1;
$imagesql = "INSERT INTO Image (ImageFile)
VALUES ('ImageFiles/".mysql_real_escape_string($_FILES['fileImage']['name'])."')";
mysql_query($imagesql);
}
答案 0 :(得分:0)
如果我已正确理解,以下代码应按预期工作。如果找到该文件,则新文件将重新生成该文件并将新条目插入数据库。 如果找不到该文件,则将从您的表中删除该数据库条目。
// Stores the final result
// 0 = File wasnt uploaded and the row has been removed from table
// 1 = File was uploaded and the row has added to the table
$result = 0;
if (is_file("ImageFiles/" . $_FILES['fileImage']['name'])) {
move_uploaded_file($_FILES["fileImage"]["tmp_name"], "ImageFiles/" . $_FILES["fileImage"]["name"]);
$imagesql = "INSERT INTO Image (ImageFile) VALUES ('ImageFiles/".mysql_real_escape_string($_FILES['fileImage']['name'])."')";
mysql_query($imagesql);
// Mark result as 1 - we have added the file to teh folder and a entry to the table
$result = 1;
} else {
$imagecancelsql = "DELETE FROM Image WHERE ImageFile = 'ImageFiles/" . mysql_real_escape_string($_FILES['fileImage']['name'])."'";
mysql_query($imagecancelsql);
}