-1

我有一个带有上传字段的表单,它工作正常。它上传并且一切都很好,除了上传字段为空时。数据库表中的字段也变为空白,其中没有任何内容,甚至没有旧图像条目!

我的表格:

<form enctype="multipart/form-data" action="add.php" method="POST"> 
Name: <input type="text" name="name"><br> 
E-mail: <input type="text" name = "email"><br> 
Phone: <input type="text" name = "phone"><br> 
Photo: <input type="file" name="site_logo"><br> 
<input type="submit" value="Add"> 
</form>

PHP代码:

<?php
    $target = "../upload/";
    $target = $target . basename($_FILES['site_logo']['name']);?>

<?php
  move_uploaded_file($_FILES['site_logo']['tmp_name'], $target);
  // output a list of the fields that had errors
     if (!empty($errors)) {
       echo "<p class=\"errors\">";
       echo "Please review the following fields:<br />";

          foreach($errors as $error) {
       echo " - " . $error . "<br />";
   }
       echo "</p>";
       }
?>

查询:

$site_logo=($_FILES['site_logo']['name']);


                $query = "UPDATE ss_settings SET 
                            site_logo = '{$site_logo}'
                        WHERE id = 1 ";
                $result = mysql_query($query, $connection);

我已经设置了数据库连接和更新查询以及所有内容。刚刚发布了流程代码,所以你们很清楚。当字段为空时,我只希望它什么都不做。

4

5 回答 5

1

查看解释的错误消息http://www.php.net/manual/en/features.file-upload.errors.php

要检查文件是否未上传:

if ($_FILES['site_logo']['error'] === UPLOAD_ERR_NO_FILE)

更好的方法是检查是否没有错误。

if ($_FILES['site_logo']['error'] === UPLOAD_ERR_OK)

于 2013-06-14T20:55:38.550 回答
0

就我个人而言,我不会对文件使用未经清理的名称,但在您的情况下,您需要做的就是在进行查询之前检查有效的文件上传。

所以像(在PDO函数mysql_*被弃用时):

// first line borrowed from @DaveChen, +1 for that
if ($_FILES['site_logo']['error'] === UPLOAD_ERR_OK)
{
  $stmt = $db->prepare("UPDATE `ss_settings` SET 
                            `site_logo` = :site_logo
                        WHERE `id` = :id ";

  // bind variables
  $stmt->bindValue(':site_logo', $_FILES['site_logo']['name'], PDO::PARAM_STR);
  $stmt->bindValue(':id', $the_ID, PDO::PARAM_INT);

  // execute query
  $stmt->execute();
}
于 2013-06-14T21:37:38.913 回答
0

如果您的查询是 UPDATE 语句,则不应更改它,也可以尝试使用

<?php
// ...
if($_FILES['site_logo']['name'] == NULL){
   // do stuff when no file field is set
}else{
   // do stuff when file is set
}
// ...
?>
于 2013-06-14T21:00:44.480 回答
-1

也许尝试这样的事情来防止处理空白上传:

if($_FILES['site_logo']['error']==0) { 
  // process 
} else { 
  // handle the error 
}

http://php.net/manual/en/features.file-upload.errors.php

于 2013-06-14T20:56:09.640 回答
-1

您的问题是您只是假设已成功上传。永远不要假设成功。始终检查故障。PHP['error']在 $_FILES 中提供参数是有原因的。用它:

if ($_FILES['site_logo']['error'] == UPLOAD_ERR_OK) {
   ... upload was successful
} else { 
   die("Upload failed with error code: " . $_FILES['site_logo']['error']);
}

错误代码在这里定义:http ://www.php.net/manual/en/features.file-upload.errors.php

您将要检查代码 4 ( UPLOAD_ERR_NO_FILE),这意味着用户根本没有上传任何内容。

于 2013-06-14T20:56:13.880 回答