gpt4 book ai didi

php - 图像重新选择php

转载 作者:行者123 更新时间:2023-11-29 06:56:54 25 4
gpt4 key购买 nike

我有一个表格,其中每行都有一个图像和一些文本。目前,当我更新内容而不选择图像时,图像的数据库字段会被清除。但是,如果没有选择图像,我想保留旧图像。

我怎样才能做到这一点?

作为注释,我知道 mysql_* 函数已被弃用。

<?php

include("db/db.php");

$select_db = "select * from aboutus WHERE id=1";
$run_news = mysql_query($select_db);

while ($row = mysql_fetch_array($run_news)) {
$id = $row['id'];
$image = $row['image'];
$content = $row['content'];
}
?>
<div class="box box-primary">
<div class="box-header with-border">
<h3 class="box-title">Update About Content</h3>
</div>
<!-- /.box-header -->
<!-- form start -->
<form role="form" method="post" action="aboutcontent.php?id=1" enctype="multipart/form-data">
<div class="box-body">

<div class="form-group">
<label for="exampleInputFile">Reselect Image *(H=530px, W=800px)</label>
<input type="file" name="user_image" id="exampleInputFile">
</div>

<div class="form-group">
<label >Content</label><br>
<textarea name="content" class="tinymce" class="form-control" rows="15"><?php echo $content; ?></textarea>
</div>
</div>
<!-- /.box-body -->

<div class="box-footer">
<button type="submit" name="update" class="btn btn-primary">Update</button>
</div>
</form>
</div>

<?php

include("db/db.php");

// Code for UPDATE button
if (isset($_POST['update'])) {

$content = $_POST['content'];

$imgFile = $_FILES['user_image']['name'];
$tmp_dir = $_FILES['user_image']['tmp_name'];
$imgSize = $_FILES['user_image']['size'];

if ($imgFile) {
$upload_dir = 'images/about/'; // upload directory
$imgExt = strtolower(pathinfo($imgFile, PATHINFO_EXTENSION)); // get image extension
$valid_extensions = array('jpeg', 'jpg', 'png', 'gif'); // valid extensions
$userpic = rand(1000, 1000000) . "." . $imgExt;

if (in_array($imgExt, $valid_extensions)) {
if ($imgSize < 5000000) {
unlink($upload_dir . $row['image']);
move_uploaded_file($tmp_dir, $upload_dir . $userpic);
}
else {
$errMSG = "Sorry, your file is too large it should be less then 5MB";
}
}
else {
$errMSG = "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
}
}
else {
// if no image selected the old image remain as it is.
$userpic = $row['image']; // old image from database
}

// if no error occured, continue ....
$sql = "UPDATE aboutus SET image='$userpic', content='$content' WHERE id=1";
$query = mysql_query($sql);
if (!$query) {
die('Invalid query: ' . mysql_error());
}
else {
echo "<script>alert('Successfully Updated!!!'); window.location='index.php?aboutcontent'</script>";
}
}

?>

最佳答案

通过检查文件是否已提交可以轻松解决该问题:

if(!empty($userpic)){
// SQL update here
} else {
// No file submitted so don't update
}

您获得空 mysql 字段的原因是因为您正在使用空变量更新该字段。

关于php - 图像重新选择php,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45200929/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com