0

我有一个文件可以移动到两个地方,具体取决于用户在单独的页面上单击了哪个按钮:

目前我已经说明文件是否移动到“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);

      }
4

1 回答 1

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);
}
于 2012-05-16T10:58:39.890 回答