php - 多个图像上传并保存到数据库的路径

标签 php jquery mysql sql database

我正在编写一个脚本,该脚本可以上传多张图片并将路径保存到数据库以分别获取每条记录中的图片。图片上传正常,但数据库中的图片名称以以下格式存储 uploads/image_name.png 实际上应该只是 image_name.png。此外,当我上传多张图片时,会在数据库中为每张图片创建一条单独的记录。我想在同一个字段中显示它们。这是我使用 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
        $img = implode('',$_FILES['file']['name']);
        $target_path = $target_path . md5(uniqid()) . "." . $ext[count($ext) - 1];
        $title = (!empty($_POST['ad_title']))?$_POST['ad_title']:null;
        $cat = (!empty($_POST['ad_cat']))?$_POST['ad_cat']:null;
        $des = (!empty($_POST['ad_des']))?$_POST['ad_des']:null;
        $name = (!empty($_POST['ad_name']))?$_POST['ad_name']:null;
        $email = (!empty($_POST['ad_email']))?$_POST['ad_email']:null;
        $phone = (!empty($_POST['ad_phone']))?$_POST['ad_phone']:null;
        $state = (!empty($_POST['ad_state']))?$_POST['ad_state']:null;

        //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] < 1024000) //Approx. 1mb files can be uploaded.
                && in_array($file_extension, $validextensions)) {
            if (move_uploaded_file($_FILES['file']['tmp_name'][$i], $target_path)) {

                $sql = "INSERT INTO ad_posting(img_name, ad_title, ad_cat, ad_des, ad_name, ad_email, ad_phone, ad_state)VALUES('$target_path', '$title','$cat','$des','$name','$email','$phone','$state')";
                $frc = mysql_query($sql);
                if ($frc){
                echo "Success";
                }else{
                echo "Not Successful";
                }

                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/>';
        }
    }
}
?>

这是我正在使用的 javascript 代码。

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();
        }
    });
});

我犯了什么错误?请帮我解决问题。

最佳答案

从 uploads/image_name.png 到 image_name.png。

$filename = 'uploads/image_name.png';
basename($filename);

在你的数据库中

$sql = "INSERT INTO ad_posting(img_name, ad_title, ad_cat, ad_des, ad_name, ad_email, ad_phone, ad_state)VALUES('$target_path', '$title','$cat','$des','$name','$email','$phone','$state')";

如果 $target_path 有 uploads/image_name.png 则

$target_path = basename($target_path);

如果您想要同一字段中所有图像的名称,您可以使用 implode()。

关于php - 多个图像上传并保存到数据库的路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28601010/

相关文章:

php - 当mysql服务器宕机时触发邮件

php - 在 Laravel 的路由中使用 {id}

mysql - Laravel groupBy 排名导致多个分组行

php - 使用 +1 | 增加包含文本 + 数字的 DB 值 | WordPress的

mysql - 使用 DATE_ADD 从 db2 到 mysql

php - 当我使用变量后跟大于 9 的数字时,我的代码 (php/js) 会感到困惑

jquery - MVC JQuery DatePicker 无法在 ie 中工作(在 Chrome 中工作)

javascript - Backbonejs 集合获取错误检测 XHR 对象

javascript - 从嵌套元素中检索链接

php - 想同时使用 GET 和 POST 方法