【发布时间】:2016-01-09 07:13:57
【问题描述】:
我正在使用下面的代码来更新我的经典(书籍)数据库中的字段。问题是它无法保留早期的图像,当我只更新文本字段时,即。它用空白(或类似空白的东西)覆盖图像详细信息字段,因此显示的是更新的文本字段,但图像链接损坏。
if (!empty($_FILES["image2"]))
{
$ed_author = get_post($conn, 'ed_author');
$ed_title = get_post($conn, 'ed_title');
$ed_category = get_post($conn, 'ed_category');
$ed_year = get_post($conn, 'ed_year');
$hid_isbn = get_post($conn, 'hid_isbn');
$filetmp = $_FILES["image2"]["tmp_name"];
$filename = $_FILES["image2"]["name"];
$filetype = $_FILES["image2"]["type"];
$filepath = "images/".$filename;
move_uploaded_file($filetmp, $filepath);
$query = "UPDATE classics SET author='$ed_author', title='$ed_title', type='$ed_category', year='$ed_year', filename='$filename', filepath='$filepath', filetype='$filetype'WHERE isbn='$hid_isbn'";
$result = $conn->query($query);
if (!$result) echo "EDIT with image failed: $query<br>" .
$conn->error . "<br><br>";
$result = $conn->query($query);
}
else{
$ed_author = get_post($conn, 'ed_author');
$ed_title = get_post($conn, 'ed_title');
$ed_category = get_post($conn, 'ed_category');
$ed_year = get_post($conn, 'ed_year');
$hid_isbn = get_post($conn, 'hid_isbn');
$oldfilename = get_post($conn, 'oldfilename');
$oldfilepath = get_post($conn, 'oldfilepath');
$oldfiletype = get_post($conn, 'oldfiletype');
$query = "UPDATE classics SET author='$ed_author', title='$ed_title', type='$ed_category', year='$ed_year', filename='$oldfilename', filepath='$oldfilepath', filetype='$oldfiletype' WHERE isbn='$hid_isbn'";
$result = $conn->query($query);
if (!$result) echo "EDIT with image failed: $query<br>" .
$conn->error . "<br><br>";
}
我知道问题在于:当没有添加新图像时,image2 永远不会测试为空,因此仍会转到 if 块 (!empty($_FILES["image2"]))` 而不是 else。那么当没有选择图像时,我应该如何检查 image2 呢?不胜感激。
另外,为了更完整,这里是表格,并附上一张记录的图像,在更新后没有添加新图像,图像链接损坏:
<form action="sqltest.php" method="post" enctype="multipart/form-data"><pre>
Author <input type="text" name="ed_author" value="<?php echo $row[0]; ?>">
Title <input type="text" name="ed_title" value="<?php echo $row[1]; ?>">
Category <input type="text" name="ed_category" value="<?php echo $row[2]; ?>">
Year <input type="text" name="ed_year" value="<?php echo $row[3]; ?>">
ISBN <input type="text" name="hid_isbn" value="<?php echo $row[4]; ?>"readonly>
<input type="hidden" name="oldfilename" value="<?php echo $row[6]; ?>">
<input type="hidden" name="oldfilepath" value="<?php echo $row[7]; ?>">
<input type="hidden" name="oldfiletype" value="<?php echo $row[8]; ?>">
<input type="file" name="image2">
<input type="hidden" name="edit" value="yes">
<input type="submit" name="btn2" value="SUBMIT EDIT">
</pre></form>
【问题讨论】:
标签: php sql image forms sql-update