How to keep the previous uploaded image (in db) after submitting a form without selecting a new image to be uploaded

女生的网名这么多〃 提交于 2020-08-02 08:00:50

问题


I have a simple form for creating an article: Title,image,category,body , etc.. My problem is with the image input.

Selecting a new one and submitting everything works fine:

  • the image is being uploaded to the server
  • the title of the image is being saved to db
  • and i can print it in the article.

By editing the whole form, filling all fields but leaving the image field as it is, and finally submitting, the image field value in db is changing to nothing.

How can i configure the php file, so every time the user submits the form without selecting an image (if there was an image pre uploaded in that article ) keep as submitted the previous image (from db) instead of nothing.?


If these informations can be of any help:

I can print the image like this : <?php echo '<img src="'.$results['article']->img.'" width="100px">'; ?>

Simple input field for image:

<input type="file" name="fileToUpload" id="fileToUpload"  value="<?php echo $results['article']->img ?>" />

回答1:


What about something like this?

if(!empty($_FILES['fileToUpload']['name'])) //new image uploaded
{
   //process your image and data
   $sql = "UPDATE table SET name=$someName, image=$someImageName,... WHERE id = $someId";//save to DB with new image name
}
else // no image uploaded
{
   // save data, but no change the image column in MYSQL, so it will stay the same value
   $sql = "UPDATE table SET name=$someName,... WHERE id = $someId";//save to DB but no change image column
}
//process SQL query in $sql



回答2:


Make a if clause that checks if fileupload input is empty or not. If it is empty do not execute query.

Use input type="file" without attribute value.

<input type="file" name="fileToUpload" id="fileToUpload" />

Here is example for if clause

if(!empty($_FILES['fileToUpload']['name'])) {
        $origFile = $_FILES['fileToUpload']['name'];
        $tempFile = $_FILES['fileToUpload']['tmp_name'];
        $sizeFile = $_FILES['fileToUpload']['size'];

        /* UPLOAD CODE GOES HERE */
    }



回答3:


It worked , really thanks

short solution

  1. check the file is not empty: if(!empty($_FILES['fileToUpload']['name']))
  2. Take update query with mentioning image column in your table in IF statement, if images not uploaded, then it will upload.
  3. Take update query without mentioning image column in your table in ELSE statement,if file is empty, it will upload

CONCLUSION

Next time when you update any other field the image won't get disappeared, meaning file path wont be empty in your database, and if already present it won't change unless you manually change it..



来源:https://stackoverflow.com/questions/29487334/how-to-keep-the-previous-uploaded-image-in-db-after-submitting-a-form-without

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!