我有一个上传字段的表单,它工作得很好。它上传,一切都很好,除了上传字段为空。数据库表中的字段也变为空白,其中没有任何内容,甚至没有旧的图像条目!
我的形式:
<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);
我已经设置了数据库连接和更新查询等等。只是把程序代码贴出来了,这样你们就清楚了。我只想让它在字段为空时什么也不做
查看解释的错误消息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)
如果你的查询是一个UPDATE语句,你不应该改变它,你也可以尝试使用
<?php
// ...
if($_FILES['site_logo']['name'] == NULL){
// do stuff when no file field is set
}else{
// do stuff when file is set
}
// ...
?>
就我个人而言,我不会为文件使用未经处理的名称,但在这种情况下,您需要做的就是在执行查询之前检查有效的文件上传。
因此类似(在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();
}
也许可以尝试这样做来防止处理空白上传:
if($_FILES['site_logo']['error']==0) {
// process
} else {
// handle the error
}
http://php.net/manual/en/features.file-upload.errors.php 您的问题是您只是简单地假设已经成功地进行了上传。永远不要假定成功。总是检查失败。PHP在$_FILES中提供['error']
参数是有原因的。使用它:
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
),这意味着用户根本没有上传任何内容。