Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/88.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
通过PHP上传多个图像并保存所有图像';mysql中表的一行中的名称_Php_Jquery_Html_Mysql_Ajax - Fatal编程技术网

通过PHP上传多个图像并保存所有图像';mysql中表的一行中的名称

通过PHP上传多个图像并保存所有图像';mysql中表的一行中的名称,php,jquery,html,mysql,ajax,Php,Jquery,Html,Mysql,Ajax,我有一个php上传脚本,其中有2个文件来处理上传的图像。 第一个文件包含html表单和ajax脚本。这个脚本可以很好地上传一个图像,并将图像名称和图像补丁保存到mysql表中 看看代码: Upload.php: <?php if($loggedin) { $contents = " <frame> <html> <head> <meta http-equiv=\"Content-Type\" content=\"text/html;

我有一个php上传脚本,其中有2个文件来处理上传的图像。 第一个文件包含html表单和ajax脚本。这个脚本可以很好地上传一个图像,并将图像名称和图像补丁保存到mysql表中

看看代码:

Upload.php:

<?php    
if($loggedin) {
    $contents = "
<frame>
<html>
<head>
<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />
<title>Ajax Upload and Resize with jQuery and PHP - Demo</title>
<script type=\"text/javascript\" src=\"Images/js/jquery-1.10.2.min.js\"></script>
<script type=\"text/javascript\" src=\"Images/js/jquery.form.min.js\"></script>

<script type=\"text/javascript\">
$(document).ready(function() { 

    var progressbox     = $('#progressbox');
    var progressbar     = $('#progressbar');
    var statustxt       = $('#statustxt');
    var completed       = '0%';

    var options = { 
            target:   '#output',   // target element(s) to be updated with server response 
            beforeSubmit:  beforeSubmit,  // pre-submit callback 
            uploadProgress: OnProgress,
            success:       afterSuccess,  // post-submit callback 
            resetForm: true        // reset the form after successful submit 
        }; 

     $('#MyUploadForm').submit(function() { 
            $(this).ajaxSubmit(options);            
            // return false to prevent standard browser submit and page navigation 
            return false; 
        });

//when upload progresses    
function OnProgress(event, position, total, percentComplete)
{
    //Progress bar
    progressbar.width(percentComplete + '%') //update progressbar percent complete
    statustxt.html(percentComplete + '%'); //update status text
    if(percentComplete>50)
        {
            statustxt.css('color','#fff'); //change status text to white after 50%
        }
}

//after succesful upload
function afterSuccess()
{
    $('#submit-btn').show(); //hide submit button
    $('#loading-img').hide(); //hide submit button

}

//function to check file size before uploading.
function beforeSubmit(){
    //check whether browser fully supports all File API
   if (window.File && window.FileReader && window.FileList && window.Blob)
    {

        if( !$('#imageInput').val()) //check empty input filed
        {
            $(\"#output\").html(\"Are you kidding me?\");
            return false
        }

        var fsize = $('#imageInput')[0].files[0].size; //get file size
        var ftype = $('#imageInput')[0].files[0].type; // get file type

        //allow only valid image file types 
        switch(ftype)
        {
            case 'image/png': case 'image/gif': case 'image/jpeg': case 'image/pjpeg':
                break;
            default:
                $(\"#output\").html(\"<b>\"+ftype+\"</b> Unsupported file type!\");
                return false
        }

        //Allowed file size is less than 1 MB (1048576)
        if(fsize>8388608) 
        {
            $(\"#output\").html(\"<b>\"+bytesToSize(fsize) +\"</b> Too big Image file! <br />Please reduce the size of your photo using an image editor.\");
            return false
        }

        //Progress bar
        progressbox.show(); //show progressbar
        progressbar.width(completed); //initial value 0% of progressbar
        statustxt.html(completed); //set status text
        statustxt.css('color','#000'); //initial color of status text


        $('#submit-btn').hide(); //hide submit button
        $('#loading-img').show(); //hide submit button
        $(\"#output\").html(\"\");  
    }
    else
    {
        //Output error to older unsupported browsers that doesn't support HTML5 File API
        $(\"#output\").html(\"Please upgrade your browser, because your current browser lacks some new features we need!\");
        return false;
    }
}

//function to format bites bit.ly/19yoIPO
function bytesToSize(bytes) {
   var sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];
   if (bytes == 0) return '0 Bytes';
   var i = parseInt(Math.floor(Math.log(bytes) / Math.log(1024)));
   return Math.round(bytes / Math.pow(1024, i), 2) + ' ' + sizes[i];
}

}); 

</script>
<link href=\"Images/style/style.css\" rel=\"stylesheet\" type=\"text/css\">
</head>
<body>
<div id=\"upload-wrapper\">
<div align=\"center\">
<h3>Upload your Image</h3>
<span class=\"\">Image Type allowed: Jpeg, Jpg, Png and Gif. | Maximum Size 8 MB</span>
<form action=\"Process.php\" onSubmit=\"return false\" method=\"post\" enctype=\"multipart/form-data\" id=\"MyUploadForm\">
<input name=\"ImageFile\" id=\"imageInput\" type=\"file\" />
<input type=\"submit\"  id=\"submit-btn\" value=\"Upload\" />
<img src=\"Images/images/ajax-loader.gif\" id=\"loading-img\" style=\"display:none;\" alt=\"Please Wait\"/>
</form>
<div id=\"progressbox\" style=\"display:none;\"><div id=\"progressbar\"></div ><div id=\"statustxt\">0%</div></div>
<div id=\"output\"></div>
</div>
</div>

</body>
</html>
</frame>
                ";
}else header("Location: login.php?return=upload.php");
?>
<?php
if(isset($_POST))
{
    ############ Edit settings ##############
    $ThumbSquareSize        = 100; //Thumbnail will be 200x200
    $BigImageMaxSize        = 300; //Image Maximum height or width
    $ThumbPrefix            = "thumb_"; //Normal thumb Prefix
    $DestinationDirectory   = '/www/site/Images/uploads/'; //specify upload directory ends with / (slash)
    $Quality                = 90; //jpeg quality
    ##########################################

    //check if this is an ajax request
    if (!isset($_SERVER['HTTP_X_REQUESTED_WITH'])){
        die();
    }

    // check $_FILES['ImageFile'] not empty
    if(!isset($_FILES['ImageFile']) || !is_uploaded_file($_FILES['ImageFile']['tmp_name']))
    {
            die('Something wrong with uploaded file, something missing!'); // output error when above checks fail.
    }

    // Random number will be added after image name
    $RandomNumber   = rand(0, 9999999999999); 

    $ImageName      = str_replace(' ','-',strtolower($_FILES['ImageFile']['name'])); //get image name
    $ImageSize      = $_FILES['ImageFile']['size']; // get original image size
    $TempSrc        = $_FILES['ImageFile']['tmp_name']; // Temp name of image file stored in PHP tmp folder
    $ImageType      = $_FILES['ImageFile']['type']; //get file type, returns "image/png", image/jpeg, text/plain etc.

    //Let's check allowed $ImageType, we use PHP SWITCH statement here
    switch(strtolower($ImageType))
    {
        case 'image/png':
            //Create a new image from file 
            $CreatedImage =  imagecreatefrompng($_FILES['ImageFile']['tmp_name']);
            break;
        case 'image/gif':
            $CreatedImage =  imagecreatefromgif($_FILES['ImageFile']['tmp_name']);
            break;          
        case 'image/jpeg':
        case 'image/pjpeg':
            $CreatedImage = imagecreatefromjpeg($_FILES['ImageFile']['tmp_name']);
            break;
        default:
            die('Unsupported File!'); //output error and exit
    }

    //PHP getimagesize() function returns height/width from image file stored in PHP tmp folder.
    //Get first two values from image, width and height. 
    //list assign svalues to $CurWidth,$CurHeight
    list($CurWidth,$CurHeight)=getimagesize($TempSrc);

    //Get file extension from Image name, this will be added after random name
    $ImageExt = substr($ImageName, strrpos($ImageName, '.'));
    $ImageExt = str_replace('.','',$ImageExt);

    //remove extension from filename
    $ImageName      = preg_replace("/\\.[^.\\s]{3,4}$/", "", $ImageName); 

    //Construct a new name with random number and extension.
    $NewImageName = $ImageName.'-'.$RandomNumber.'.'.$ImageExt;
    $NewThumbImageName = $ThumbPrefix.$NewImageName;

    //set the Destination Image
    $thumb_DestRandImageName    = $DestinationDirectory.$ThumbPrefix.$NewImageName; //Thumbnail name with destination directory
    $DestRandImageName          = $DestinationDirectory.$NewImageName; // Image with destination directory

    //Resize image to Specified Size by calling resizeImage function.
    if(resizeImage($CurWidth,$CurHeight,$BigImageMaxSize,$DestRandImageName,$CreatedImage,$Quality,$ImageType))
    {
        //Create a square Thumbnail right after, this time we are using cropImage() function
        if(!cropImage($CurWidth,$CurHeight,$ThumbSquareSize,$thumb_DestRandImageName,$CreatedImage,$Quality,$ImageType))
            {
                echo 'Error Creating thumbnail';
            }
        /*
        We have succesfully resized and created thumbnail image
        We can now output image to user's browser or store information in the database
        */

        // Insert info into database table!
    $chkquery = mysql_query("SELECT * FROM `ID_Card` WHERE `UserName`='{$ir['username']}'")or die(mysql_error());
        if(mysql_num_rows($chkquery) > 0){

            while($chkquerys = @mysql_fetch_array($chkquery)){
            $answer=$chkquerys['Approved'];
                if($answer == 1) {
                        echo '<table width="100%" border="0" cellpadding="4" cellspacing="0">';
                        echo '<tr>';
                        echo '<td align="center"> some text:<br><br> <img src="'.$chkquerys['ImageName'].'" alt="Image"></td>';
                        echo '</tr>';
                        echo '</table>';
                        die();

                }if($answer == 0) {
                        echo '<table width="100%" border="0" cellpadding="4" cellspacing="0">';
                        echo '<tr>';
                        echo '<td align="center"> some text:<br><br> <img src="'.$chkquerys['ImagePath'].''.$chkquerys['ImageName'].'" alt="Image"></td>';
                        echo '</tr>';
                        echo '</table>';
                        die();
                }

            }
        }   else{
        /* DB Connect code goes here... */
        mysql_query("INSERT INTO `Images`(Id,`UserName`,`ImageName`,`ThumbName`,`ImagePath`,`Approved`,`Ip`,`Date`)
        VALUES (Null,'Null','$NewImageName','$NewThumbImageName','Images/uploads/','0','IP',unix_timestamp())")or die(mysql_error());}

        echo '<table width="100%" border="0" cellpadding="4" cellspacing="0">';
        echo '<tr>';
        echo '<td align="center">Dear '.$ir['username'].', your Image was uploaded successfully. please waiting for review and verify.</td>';
        echo '</tr><tr>';
        echo '<td align="center"><img src="Images/uploads/'.$NewImageName.'" alt="Resized Image"></td>';
        echo '</tr>';
        echo '</table>';


        }else{
        die('Resize Error'); //output error
    }
}


// This function will proportionally resize image 
function resizeImage($CurWidth,$CurHeight,$MaxSize,$DestFolder,$SrcImage,$Quality,$ImageType)
{
    //Check Image size is not 0
    if($CurWidth <= 0 || $CurHeight <= 0) 
    {
        return false;
    }

    //Construct a proportional size of new image
    $ImageScale         = min($MaxSize/$CurWidth, $MaxSize/$CurHeight); 
    $NewWidth           = ceil($ImageScale*$CurWidth);
    $NewHeight          = ceil($ImageScale*$CurHeight);
    $NewCanves          = imagecreatetruecolor($NewWidth, $NewHeight);

    // Resize Image
    if(imagecopyresampled($NewCanves, $SrcImage,0, 0, 0, 0, $NewWidth, $NewHeight, $CurWidth, $CurHeight))
    {
        switch(strtolower($ImageType))
        {
            case 'image/png':
                imagepng($NewCanves,$DestFolder);
                break;
            case 'image/gif':
                imagegif($NewCanves,$DestFolder);
                break;          
            case 'image/jpeg':
            case 'image/pjpeg':
                imagejpeg($NewCanves,$DestFolder,$Quality);
                break;
            default:
                return false;
        }
    //Destroy image, frees memory   
    if(is_resource($NewCanves)) {imagedestroy($NewCanves);} 
    return true;
    }

}

//This function corps image to create exact square images, no matter what its original size!
function cropImage($CurWidth,$CurHeight,$iSize,$DestFolder,$SrcImage,$Quality,$ImageType)
{    
    //Check Image size is not 0
    if($CurWidth <= 0 || $CurHeight <= 0) 
    {
        return false;
    }

    //abeautifulsite.net has excellent article about "Cropping an Image to Make Square bit.ly/1gTwXW9
    if($CurWidth>$CurHeight)
    {
        $y_offset = 0;
        $x_offset = ($CurWidth - $CurHeight) / 2;
        $square_size    = $CurWidth - ($x_offset * 2);
    }else{
        $x_offset = 0;
        $y_offset = ($CurHeight - $CurWidth) / 2;
        $square_size = $CurHeight - ($y_offset * 2);
    }

    $NewCanves  = imagecreatetruecolor($iSize, $iSize); 
    if(imagecopyresampled($NewCanves, $SrcImage,0, 0, $x_offset, $y_offset, $iSize, $iSize, $square_size, $square_size))
    {
        switch(strtolower($ImageType))
        {
            case 'image/png':
                imagepng($NewCanves,$DestFolder);
                break;
            case 'image/gif':
                imagegif($NewCanves,$DestFolder);
                break;          
            case 'image/jpeg':
            case 'image/pjpeg':
                imagejpeg($NewCanves,$DestFolder,$Quality);
                break;
            default:
                return false;
        }
    //Destroy image, frees memory   
    if(is_resource($NewCanves)) {imagedestroy($NewCanves);} 
    return true;

    }

}
这可能吗?
谢谢:)

尝试设置与数组相同的名称,例如:

<label>Image #1:</label><input name="ImageFile[]" type="file" >
<label>Image #2:</label><input name="ImageFile[]" type="file" >
<label>Image #3:</label><input name="ImageFile[]" type="file" >
所以现在你可以拥有你想要的任何图像。将结果放入一个数组($array)中,然后像这样分解(或内爆):'explode(',',$array)

如果需要多个图像上传器,请在输入中添加多个图像:

<label>Image #1:</label><input name="ImageFile[]" type="file" multiple="multiple">
图像#1:

这一切都在我自己的代码中起作用,我只是不记得爆炸或内爆、
multiple=“multiple”
multiple
multiple=“true”
。不过,你可以用谷歌搜索一下。

我们绝对不会浏览所有这些代码。将问题定位为相关的几行。“这可能吗?”是的。“谢谢:)”不客气:)现在尝试一下,如果您遇到问题,请发布一个关于特定问题的特定问题。@OhgoodWhy嗨,您可以从这里阅读我的问题:我想上传3个图像,并将所有上传的图像保存到数据库表中的一行。可能吗?谢谢你的回答。:)@PatrickQ正如我所说,我的问题是我不知道如何将所有图像名称保存在DB表的一行中!是的,你知道。您在问题中发布了查询(或至少非常接近您想要的内容)。谢谢@Bene,您的回答很有用,但我仍然对mysql查询有问题。对于您的代码,如果有3个文件要上传,循环将重复3次,如果循环中有查询,则在数据库中创建3行。我只想把所有的图像名称都放在一行中。这件事你也能帮我吗?是的。正如我所说,在循环中,您还没有执行任何SQL。分解(或内爆。该死的,我现在就用谷歌搜索一下)好的,所以内爆将数组放入字符串中。内爆(“,”,$array)返回file1、file2、file3。。。当然,当您在“mysql”中添加第一个时,您只需在
中插入任何
(图像)值(“.$infrade(“,”,$array)。”)(您必须正确地转义并验证所有这些)谢谢@Bene,非常有用,现在我知道我应该在google中搜索什么才能获得更好的结果。:)使用explode或imploade,我可以将图像的名称保存在一行的不同列中吗?我真的不理解这个问题。整列和整排的事情把我弄糊涂了。我猜您希望在一个条目中包含多个字段,而我知道您希望在一个字段中包含所有图像
<label>Image #1:</label><input name="ImageFile[]" type="file" >
<label>Image #2:</label><input name="ImageFile[]" type="file" >
<label>Image #3:</label><input name="ImageFile[]" type="file" >
  $array = array();
  foreach($_FILES['ImageFile'] as $img) {
     // $img['name']
     // $img['tmp']
     // ...
     // upload
     // $array[] = {{the uploaded image}}
  }
<label>Image #1:</label><input name="ImageFile[]" type="file" multiple="multiple">