将上传图片的路径保存在数据库中

Posted

技术标签:

【中文标题】将上传图片的路径保存在数据库中【英文标题】:save the path of uploaded image in database 【发布时间】:2014-11-21 17:48:26 【问题描述】:

我有一个将 5 张图片上传到服务器文件夹的表单

<form action="co_insert_office_image.php" method="post" enctype="multipart/form-data">

    <div class="col-md-6">
        <div class="form-group">
            <label class="col-lg-4 control-label">Image 1</label>
                <div class="col-lg-6">
                    <input type="file" name="file_img" />
                </div>
        </div>
    </div>

    <div class="col-md-6">
        <div class="form-group">
            <label class="col-lg-4 control-label">Image 2</label>
                <div class="col-lg-6">
                    <input type="file" name="file_img1" />
                </div>
        </div>
    </div>

    <div class="col-md-6">
        <div class="form-group">
            <label class="col-lg-4 control-label">Image 3</label>
                <div class="col-lg-6">
                    <input type="file" name="file_img2" />
                </div>
        </div>
    </div>

    <div class="col-md-6">
        <div class="form-group">
            <label class="col-lg-4 control-label">Image 4</label>
                <div class="col-lg-6">
                    <input type="file" name="file_img3" />
                </div>
        </div>
    </div>

    <div class="col-md-6">
        <div class="form-group">
            <label class="col-lg-4 control-label">Image 5</label>
                <div class="col-lg-6">
                    <input type="file" name="file_img4" />
                </div>
        </div>
    </div>

    <div class="col-md-6">
        <div class="form-group">
            <div class="col-lg-6">
                <input type="submit" name="btn_upload" value="Upload">
            </div>
        </div>
    </div>

</form>

co_insert_office_image.php

<?php
include('admin_session.php');

$con=mysqli_connect("localhost","root","","db");
// Check connection
if (mysqli_connect_errno()) 
  echo "Failed to connect to MySQL: " . mysqli_connect_error();


if(isset($_POST['btn_upload']))

    $officeid = $_GET['id'];
    echo $officeid;

    $filetmp  = $_FILES["file_img"]["tmp_name"];
    $filename = $_FILES["file_img"]["name"];
    //$filetype = $_FILES["file_img"]["type"];
    $filepath = "uploads/".$filename;
    move_uploaded_file($filetmp,$filepath);

    $filetmp1  = $_FILES["file_img1"]["tmp_name"];
    $filename1 = $_FILES["file_img1"]["name"];
    //$filetype = $_FILES["file_img"]["type"];
    $filepath1 = "uploads/".$filename1;
    move_uploaded_file($filetmp1,$filepath1);

    $filetmp2  = $_FILES["file_img2"]["tmp_name"];
    $filename2 = $_FILES["file_img2"]["name"];
    //$filetype = $_FILES["file_img"]["type"];
    $filepath2 = "uploads/".$filename2;
    move_uploaded_file($filetmp2,$filepath2);

    $filetmp3  = $_FILES["file_img3"]["tmp_name"];
    $filename3 = $_FILES["file_img3"]["name"];
    //$filetype = $_FILES["file_img"]["type"];
    $filepath3 = "uploads/".$filename3;
    move_uploaded_file($filetmp3,$filepath3);

    $filetmp4  = $_FILES["file_img4"]["tmp_name"];
    $filename4 = $_FILES["file_img4"]["name"];
    //$filetype = $_FILES["file_img"]["type"];
    $filepath4 = "uploads/".$filename4;
    move_uploaded_file($filetmp4,$filepath4);

    $sql = "UPDATE  register_office set image='".$filepath."' AND image1='".$filepath1."' AND image2='".$filepath2."' AND image3='".$filepath3."' AND image4='".$filepath4."' WHERE id='".$officeid."' ";

    if (!mysqli_query($con,$sql)) 
        
            die('Error: ' . mysqli_error($con));
        
    mysqli_close($con);

?>

图像被存储在服务器文件夹中,但它们的路径没有被存储在数据库中。谁能告诉我该怎么做?我还想添加对图像大小和允许的图像扩展类型的检查。谁能指导我这些要点?

【问题讨论】:

为什么要存储路径和文件名?我认为你应该只将文件名存储到数据库中,并将文件路径放在 html img 标签中,这样将来如果你的文件路径被更改,你就不需要更新你的数据库。并检查大小使用$_FILES["file_img_name"]["size"] 【参考方案1】:

这是您可能喜欢的完整代码

multiupload.php

<html>
    <head>
        <title>Upload Multiple Images Using jquery and PHP</title>
        <!-------Including jQuery from google------>
        <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
        <script src="script.js"></script>

        <!-------Including CSS File------>
        <link rel="stylesheet" type="text/css" href="style.css">
    <body>
        <div id="maindiv">

            <div id="formdiv">
                <h2>Multiple Image Upload Form</h2>
                <form enctype="multipart/form-data" action="" method="post">
                    First Field is Compulsory. Only JPEG,PNG,JPG Type Image Uploaded. Image Size Should Be Less Than 100KB.
                    <hr/>
                    <div id="filediv"><input name="file[]" type="file" id="file"/></div><br/>

                    <input type="button" id="add_more" class="upload" value="Add More Files"/>
                    <input type="submit" value="Upload File" name="submit" id="upload" class="upload"/>
                </form>
                <br/>
                <br/>
                <!-------Including PHP Script here------>
                <?php include "upload.php"; ?>
            </div>


        </div>
    </body>
</html>

script.js

var abc = 0; //Declaring and defining global increement variable

$(document).ready(function() 

//To add new input file field dynamically, on click of "Add More Files" button below function will be executed
    $('#add_more').click(function() 
        $(this).before($("<div/>", id: 'filediv').fadeIn('slow').append(
                $("<input/>", name: 'file[]', type: 'file', id: 'file'),        
                $("<br/><br/>")
                ));
    );

//following function will executes on change event of file input to select different file   
$('body').on('change', '#file', function()
            if (this.files && this.files[0]) 
                 abc += 1; //increementing global variable by 1

                var z = abc - 1;
                var x = $(this).parent().find('#previewimg' + z).remove();
                $(this).before("<div id='abcd"+ abc +"' class='abcd'><img id='previewimg" + abc + "' src=''/></div>");

                var reader = new FileReader();
                reader.onload = imageIsLoaded;
                reader.readAsDataURL(this.files[0]);

                $(this).hide();
                $("#abcd"+ abc).append($("<img/>", id: 'img', src: 'x.png', alt: 'delete').click(function() 
                $(this).parent().parent().remove();
                ));
            
        );

//To preview image     
    function imageIsLoaded(e) 
        $('#previewimg' + abc).attr('src', e.target.result);
    ;

    $('#upload').click(function(e) 
        var name = $(":file").val();
        if (!name)
        
            alert("First Image Must Be Selected");
            e.preventDefault();
        
    );
);

style.css

@import url(http://fonts.googleapis.com/css?family=Droid+Sans);
form
    background-color:white;

#maindiv
    width:960px; 
    margin:10px auto; 
    padding:10px;
    font-family: 'Droid Sans', sans-serif;

#formdiv
    width:500px; 
    float:left; 
    text-align: center;

form
    padding: 40px 20px;
    box-shadow: 0px 0px 10px;
    border-radius: 2px;

h2
    margin-left: 30px;

.upload
    background-color:#ff0000;
    border:1px solid #ff0000;
    color:#fff;
    border-radius:5px;
    padding:10px;
    text-shadow:1px 1px 0px green;
    box-shadow: 2px 2px 15px rgba(0,0,0, .75);

.upload:hover
    cursor:pointer;
    background:#c20b0b;
    border:1px solid #c20b0b;
    box-shadow: 0px 0px 5px rgba(0,0,0, .75);

#file
    color:green;
    padding:5px; border:1px dashed #123456;
    background-color: #f9ffe5;

#upload
    margin-left: 45px;


#noerror
    color:green;
    text-align: left;

#error
    color:red;
    text-align: left;

#img 
    width: 17px;
    border: none; 
    height:17px;
    margin-left: -20px;
    margin-bottom: 91px;


.abcd
    text-align: center;


.abcd img
    height:100px;
    width:100px;
    padding: 5px;
    border: 1px solid rgb(232, 222, 189);

b
    color:red;

#formget
    float:right; 


上传.php

<?php
if (isset($_POST['submit'])) 
    $j = 0; //Variable for indexing uploaded image 

    $target_path = "uploads/"; //Declaring Path for uploaded images
    for ($i = 0; $i < count($_FILES['file']['name']); $i++) //loop to get individual element from the array

        $validextensions = array("jpeg", "jpg", "png");  //Extensions which are allowed
        $ext = explode('.', basename($_FILES['file']['name'][$i]));//explode file name from dot(.) 
        $file_extension = end($ext); //store extensions in the variable

        $target_path = $target_path . md5(uniqid()) . "." . $ext[count($ext) - 1];//set the target path with a new name of image
        $j = $j + 1;//increment the number of uploaded images according to the files in array       

      if (($_FILES["file"]["size"][$i] < 100000) //Approx. 100kb files can be uploaded.
                && in_array($file_extension, $validextensions)) 
            if (move_uploaded_file($_FILES['file']['tmp_name'][$i], $target_path)) //if file moved to uploads folder
                echo $j. ').<span id="noerror">Image uploaded successfully!.</span><br/><br/>';
             else //if file was not moved.
                echo $j. ').<span id="error">please try again!.</span><br/><br/>';
            
         else //if file size and file type was incorrect.
            echo $j. ').<span id="error">***Invalid file Size or Type***</span><br/><br/>';
        
    

?>

希望对你有用

【讨论】:

【参考方案2】:

您的 sql 语法替换和 coma(,) 出现错误

喜欢:

$sql = "UPDATE  register_office set image='".$filepath."', image1='".$filepath1."',         image2='".$filepath2."', image3='".$filepath3."', image4='".$filepath4."' WHERE id='".$officeid."' ";

查看此答案如何设置多列:setting multiple column using one update

如果图片没有上传,也会发生什么。您应该在 if 语句中生成 SQL/移动图像。

类似示例(未经测试!):

$sql = "UPDATE  $_FILES["file_img4"] SET";
if(isset( $_FILES["file_img4"]) )
    $filetmp4  = $_FILES["file_img4"]["tmp_name"];
    $filename4 = $_FILES["file_img4"]["name"];
    //$filetype = $_FILES["file_img"]["type"];
    $filepath4 = "uploads/".$filename4;
    move_uploaded_file($filetmp4,$filepath4);
    $sql .= "image4='".$filepath4."' ";

// times 5
$sql .= " WHERE id='".$officeid."' ";

【讨论】:

【参考方案3】:

首先,我要说的是,出于安全原因,需要对代码进行转义,并妥善处理。

查看PDO 和binding 您的参数以防止SQL 注入和其他潜在问题。

话虽如此,下面是您的代码,其中进行了一些更改。请注意,我没有对此进行测试,请检查脚本的语法: php -l scriptName.php

在您调试的同时,转储 SQL 以验证它是否正确,并在 MySQL 中运行。

<?php
include('admin_session.php');

$con = mysqli_connect("localhost", "root", "", "db");

// Check connection
if (mysqli_connect_errno()) 
  echo "Failed to connect to MySQL: " . mysqli_connect_error();


if(isset($_POST['btn_upload'])) 

    $officeid = $_GET['id'];
    echo $officeid;

    $files = array(
        'file_img',
        'file_img1',
        'file_img2',
        'file_img3',
        'file_img4',
    );

    $sqlData = array();
    for ($i = 0; $i <= 4; $i++) 
        /*
         * The field name: file_img
         */
        $inputName = $files[$i];
        /*
         * Table name: image, image1
         */
        $tableField = ($i > 0) ? 'image' . $i : 'image';

        /*
         * Verify the field data is there
         */
        if (isset($_FILES[$inputName])) 
            $filetmp  = $_FILES[$$inputName]["tmp_name"];
            $filename = $_FILES[$$inputName]["name"];
            // $filetype = $_FILES["file_img"]["type"];
            $filepath = "uploads/" . $filename;
            move_uploaded_file($filetmp, $filepath);

            /*
             * Set the changed image
             */
            $sqlData[] = $tableField . ' = "' $filepath . '", ';
        
    

    $sql = 'UPDATE register_office SET ';
    $sql .= implode(', ', $sqlData);
    $sql .= ' WHERE id = ' . $officeid;


    if (!mysqli_query($con,$sql)) 
        die('Error: ' . mysqli_error($con));
    

    mysqli_close($con);

【讨论】:

以上是关于将上传图片的路径保存在数据库中的主要内容,如果未能解决你的问题,请参考以下文章

C#winform 中上传图片保存到数据库中?

用fileupload上传图片,怎么获取上传后图片的相对路径

图片如何存入数据库

SpringBoot+Vue+token实现(表单+图片)上传图片地址保存到数据库。上传图片保存位置自己定义图片可以在前端回显)

如何将图片存到数据库

求ASP上传图片代码(上传图片到指定文件夹,同时获取路径保存到数据库中)