Php 忽略空白文件上载字段

Php 忽略空白文件上载字段,php,forms,file-upload,Php,Forms,File Upload,我有一个带有上传字段的表单,它工作正常。它上传,一切都很好,除了上传字段为空。数据库表中的字段也变为空白,其中没有任何内容,甚至没有旧的图像条目 我的表格: <form enctype="multipart/form-data" action="add.php" method="POST"> Name: <input type="text" name="name"><br> E-mail: <input type="text" name = "ema

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

我的表格:

<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
    $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>";
       }
?>

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

查看解释的错误消息

要检查文件是否未上载,请执行以下操作:

if($\u文件['site\u logo']['error']==上传\u ERR\u NO\u文件)

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


如果($\u文件['site\u logo']['error']==UPLOAD\u ERR\u OK)

可以尝试类似的方法来防止处理空白上传:

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

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

if ($_FILES['site_logo']['error'] == UPLOAD_ERR_OK) {
   ... upload was successful
} else { 
   die("Upload failed with error code: " . $_FILES['site_logo']['error']);
}
此处定义了错误代码:


您需要检查代码4(
UPLOAD\u ERR\u NO\u FILE
),这意味着用户根本没有上传任何内容。

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

<?php
// ...
if($_FILES['site_logo']['name'] == NULL){
   // do stuff when no file field is set
}else{
   // do stuff when file is set
}
// ...
?>

就我个人而言,我不会对文件使用未经消毒的名称,但在您的情况下,只需在执行查询之前检查有效的文件上载即可

例如(在
mysql.*
函数被弃用的情况下):


那么,为什么不实现一个
if empty
函数来阻止它进一步运行呢?我已经尝试过了,但没有成功。你会写代码吗?也许我做错了,如果你使用相同的表单,例如编辑文本数据,不需要上传文件,你应该发布你的数据库代码;问题在于如何构建查询。您好,因为在将数据输入数据库之前,您应该使用js Valiadition检查输入是否存在,并检查页面上是否存在post/get数据,即检查isset和empty Condition。这不是真正的“检查失败”,而是假设失败并检查成功。它不起作用,你能写出全部代码吗?也许我做错了。
<?php
// ...
if($_FILES['site_logo']['name'] == NULL){
   // do stuff when no file field is set
}else{
   // do stuff when file is set
}
// ...
?>
// 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();
}