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

时间:2015-02-19 07:46:50

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

我犯的错误是什么?请帮我解决一下这个问题。

1 个答案:

答案 0 :(得分:0)

从uploads / image_name.png到image_name.png。

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

在你的SQL中

$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有vale uploads / image_name.png那么

$target_path = basename($target_path);

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