这是我前面问过的一个问题的延伸,其中@eHussain是nice enough to help out with。
我有一个表单,它将各种细节插入MySQL表并上传一个文件(其名称也在数据库中注册)。这很好用。当我更新名称而不是图像时会出现问题。在这种情况下,图像名称被覆盖为“空白”,正确地将其写为文件字段中的值。
更新代码:
<?php
error_reporting(E_ALL^E_NOTICE);
define('INCLUDE_CHECK',true);
include "connect.php";
$target = "../uploads/";
$target = $target . basename( $_FILES['photo']['name']);
//This gets all the other information from the form
$name=$_POST['name'];
$url=$_POST['url'];
$description=$_POST['description'];
$pic=($_FILES['photo']['name']);
$author=$_POST['author'];
$company=$_POST['company'];
$published=$_POST['published'];
$dashboardID=$_POST['dashboardID'];
//Writes the information to the database
mysql_query("UPDATE dashboard SET name='$name', url='$url', description='$description', documentName='$pic', author='$author', company='$company', publish='$published' WHERE dashboardID='$dashboardID'");
//Writes the photo to the server
if(isset($_FILES['photo']['tmp_name'])) // check if any file is uploaded
{
if(move_uploaded_file($_FILES['photo']['tmp_name'], $target))
{
header("Location: ../dashboard.php?success=2"); } else {
header("Location: ../dashboard.php?success=0"); }
}
?>
我理解'isset'是为了避免在没有选择文件的情况下产生错误,但我不明白如何扩展它以避免更新具有空值的字段。
答案 0 :(得分:1)
在运行查询之前检查$_FILES
数组。
从那里,您可以动态构建查询(包括或排除documentName
字段),也可以获取当前值并将其分配给$pic
。
例如(未经测试)
$values = array(
'name' => $name,
'url' => $url,
// etc
);
if (isset($_FILES['photo']['name'])) {
$values['documentName'] = $_FILES['photo']['name']
}
// mysql functions are naff, use PDO
$query = 'UPDATE dashboard SET %s WHERE dashboardID = :dashboardID';
$set = array();
foreach (array_keys($values) as $col) {
$set[] = sprintf('`%s` = :%s', $col, $col);
}
$stmt = $pdo->prepare(sprintf($query, implode(', ', $set)));
$values['dashboardID'] = $dashboardID;
$stmt->execute($values);
答案 1 :(得分:0)
@rrfive,请尝试以下方法,希望它能运作,
//first put all post variable in an array
$post_data = compact($_POST);
$pic=($_FILES['photo']['name']);
//now push pic name in `$post_data`
if (!empty($pic) ) { array_push( $post_data,$pic ) }
//now use UPDATE query using `vsprintf` . but first check the order of `$post_data` @Thanks Phill
$stmt = "UPDATE dashboard SET
name='%s',
url='%s',
description='%s',
author='%s',
company='%s',
publish='%s'";
$stmt .=(!empty($pic)) ? documentName='%s', : "";
$stmt .= "WHERE dashboardID=%d";
// To check the complete query before execute. uncomment below 2 lines
//print vsprintf($stmt,$post_data);
//die;
mysql_query( vsprintf($stmt,$post_data) );
答案 2 :(得分:-1)
以下代码可以解决问题。
if(isset($_FILES)){
...stuff...
}