如果不起作用?

时间:2014-07-24 18:09:01

标签: php mysql variables if-statement file-upload

我有一个文章编辑功能,可以在选中时自动加载文章详细信息。我想在编辑期间(在编辑模式下重新提交时)查看文件是否已提交。如果未提交文件,请保持数据库中的图像URL不变,否则更改图像URL。当我在编辑期间不提交文件时,图像网址会以某种方式破坏。

$article_id = $_POST['article-id'];
$article_title = $_POST['article-title'];
$article_description = $_POST['article-description'];
$article_image = $_POST['thumbnail'];
$article_content = $_POST['article-content'];

if(!isset($_FILES['article-thumbnail']) && 
   !$_FILES['article-thumbnail']['size'] > 0){
    $query = "UPDATE article
              SET article_title = '$article_title', 
              article_description = '$article_description', 
              article_content = '$article_content', published = 'NO'
              WHERE article_id = '$article_id'";

    if (!mysql_query($query)) {
        // Handle error here
        // e.g.
        echo "Oh no! The query failed! Error: ".mysql_error();
    }

    mysql_close();
} else {
    $valid_formats = array("jpg", "png", "gif", "zip", "bmp");
    $max_file_size = 1024*100; 
    $path = "test/article_thumbnails/"; 
    $count = 0;

    $thumbnailPath = 'http://localhost:8888/test_cms/images/article-thumbnails/' . 
                      $_FILES["article-thumbnail"]["name"];

    // Loop $_FILES to exeicute all files
    foreach ($_FILES['article-thumbnail']['name'] as $f => $name) {     
        if ($_FILES['article-thumbnail']['error'][$f] == 4) {
            continue; // Skip file if any error found
        }        

        if ($_FILES['article-thumbnail']['error'][$f] == 0) {            
            if ($_FILES['article-thumbnail']['size'][$f] > $max_file_size) {
                $message[] = "$name is too large!.";
                continue; // Skip large files
            } else if( ! in_array(pathinfo($name, PATHINFO_EXTENSION), $valid_formats) ) {
                $message[] = "$name is not a valid format";
                continue; // Skip invalid file formats
            } else { // No error found! Move uploaded files 
                if(move_uploaded_file($_FILES["article-thumbnail"]["tmp_name"][$f], $path.$name))
                    $count++; // Number of successfully uploaded file
            }
        }
    }

    $query = "UPDATE article
              SET article_title = '$article_title', 
              article_description = '$article_description', 
              article_image = '$thumbnailPath', 
              article_content = '$article_content', published = 'NO'
              WHERE article_id = '$article_id'";

    if (!mysql_query($query)) {
        // Handle error here
        // e.g.
        echo "Oh no! The query failed! Error: ".mysql_error();
    }

    mysql_close();
}

正如您在else语句中看到的那样,thumbnailPath设置为文件名后面的URL:

$_FILES["article-thumbnail"]["name"];

如果我在编辑期间未提交文件,则会在没有文件名的情况下将URL写入数据库中。即使它不应该进入else子句?

0 个答案:

没有答案