表格提交不止一次

时间:2016-01-28 17:20:43

标签: php jquery ajax forms

我的表单有一个问题。我正在尝试使用ajax和php向数据库添加一些东西,但是当我第一次添加一些东西时工作正常,完美,但是当我尝试在第一个之后直接添加另一个项目时,表单被提交三次,然后当我再次尝试时,它被提交了五次....

我的ajax代码是:

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

        $("#addPetForm").submit(function(e){
            e.preventDefault();
        });
        $(document).on("click","#btn-add-pet", function(){

           var bootstrapValidator = $("#addPetForm").data('bootstrapValidator');
               bootstrapValidator.validate();
               if(bootstrapValidator.isValid()){
                    //function after succesful file upload (when server response)
                    function afterSuccess(msg)
                    {
                        bootstrapValidator.resetForm();
                        $('#input-700').fileinput('clear');
                        $("#info-middle-register").hide();
                        $("#pleaseWaitGif").hide();

                        if(msg.status == "NotUpdated"){
                            //Ako nije uspijesno dodano
                            $("#addpeterror").html(msg.result).fadeIn(400).fadeOut(10000);
                        }else if(msg.status == "Updated"){
                            $("#addpetsuccess").html(msg.result).fadeIn(400).fadeOut(10000);

                            if(msg.noPhotosAdded == "No photos added"){
                                $("#addpeterror").html("<i class=\"fa fa-exclamation-triangle\"></i> De nieuwe foto's zijn niet toegevoegd!").fadeIn(400).fadeOut(10000);
                            }
                            if(msg.noPhotosSelected == "No photos selected"){
                                $("#addpetwarning").html("<i class=\"fa fa-exclamation-circle\"></i> Er zijn geen nieuwe foto's gekozen. Het is aanbevolen om minstens één foto toe te voegen.").fadeIn(400).fadeOut(10000);
                            }
                            $("#addPetForm").find("input[type=text], textarea, select]").val("");
                            $('[name="geslacht"]').val('').selectpicker('refresh');
                            $("#oldPhotos").hide();
                            $("#cancelBack").html("<button id=\"dataTitle\" class=\"btn btn-danger btn-cancel\" data-title=\"Ga terug\"><i class=\"fa fa-arrow-left\"></i> &nbsp Terug naar profiel</button>");

                        }else if(msg.status == "NotAdded"){
                            //Ako nije uspijesno dodano
                            $("#addpeterror").html(msg.result).fadeIn(400).fadeOut(10000);
                        }else{
                            //Ako je query bio uspijesan, tj dodana je zivotinja u bazu
                            if(msg.status == "Added"){
                                $("#addpetsuccess").html(msg.result).fadeIn(400).fadeOut(10000);
                                $("#totalPets").html(msg.nrPets);

                                if(msg.noPhotosAdded == "No photos added"){
                                    $("#addpeterror").html("<i class=\"fa fa-exclamation-triangle\"></i> De foto's zijn niet toegevoegd!").fadeIn(400).fadeOut(10000);
                                }
                                if(msg.noPhotosSelected == "No photos selected"){
                                    $("#addpetwarning").html("<i class=\"fa fa-exclamation-circle\"></i> Er zijn geen foto's gekozen. Het is aanbevolen om minstens één foto toe te voegen.").fadeIn(400).fadeOut(10000);
                                }
                                $('[name="geslacht"]').val('').selectpicker('refresh');
                            }
                        }
                    }

                    //function to check file size before uploading.
                    function beforeSubmit(){
                       $("#info-middle-register").show();
                       $("#pleaseWaitGif").show(); 
                    }

                    //progress bar function
                    function OnProgress()
                    {
                        $("#info-middle-register").show();
                        $("#pleaseWaitGif").show(); 
                    }

                    var options = { 
                        beforeSubmit:  beforeSubmit,  // pre-submit callback 
                        success:       afterSuccess,  // post-submit callback 
                        uploadProgress: OnProgress, //upload progress callback 
                        dataType: "json",
                        resetForm: true        // reset the form after successful submit 
                    }; 

                 $(document).on("submit", "#addPetForm", function(e) { 
                    $(this).ajaxSubmit(options);            
                    // always return false to prevent standard browser submit and page navigation 
                    return false; 
                }); 



           }
           else return;

        });


    }); 
</script>

我的php表单是:

<div id="signupbox" style="display:block; margin:0 auto;float:none;" class="mainbox">
<div class="panel panel-info">
    <div class="panel-heading">
        <div class="panel-title"><i class="fa fa-user-plus"></i>&nbsp;&nbsp;Voeg uw verloren dier toe</div>
    </div>  
    <div class="panel-body">
        <div id="info-middle-register" style="display:none;z-index:99999999;"><img src="img/ajax-loader.gif" title="Even geduld aub"></div>

        <!-- Ispis poruka vracenih iz dier-toevoegen-submit -->
        <div id="addpetsuccess" style="display:none;text-align:center;" class="alert alert-success alert-dismissible">
            <button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button>
        </div>
        <div id="addpeterror" style="display:none;text-align:center;" class="alert alert-danger alert-dismissible">
            <button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button>
        </div>
        <div id="addpetwarning" style="display:none;text-align:center;" class="alert alert-warning alert-dismissible">
            <button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button>
        </div>

        <form id="addPetForm" action="dier-toevoegen-submit.php" class="form-horizontal" role="form" method="post" enctype="multipart/form-data">

            <div class="help-block" style="text-align:center;margin:10px 0 30px 0;">
                Beschrijf uw huisdier via het onderstaande formulier zo <b>volledig</b> mogelijk (het is ook aanbevolen om minstens één foto toe te voegen) zodat de mensen uw dier gemakkelijker kunnen herkennen.
            </div>  
            <input type="hidden" value="<?php echo $_POST["changeID"]; ?>" name="txtHiddenID" >
            <div class="left-inner-addon form-group col-lg-6" style="margin: 0 0 15px 0;">
                <span><i class="fa fa-paw"></i></span>
                <input id="addPetName" type="text" class="form-control" name="name" placeholder="Naam van uw dier" required value="<?php echo $petNameOld; ?>">
            </div>

            <div class="left-inner-addon form-group col-lg-6" style="margin: 0 0 15px 0;">
                <span><i class="fa fa-reddit-alien"></i></span>
                <input id="addPetBreed" type="text" class="form-control" name="breed" placeholder="Ras van uw dier" required value="<?php echo $petBreedOld; ?>">
            </div>
            <div style="clear:both"></div>
            <div class="left-inner-addon form-group col-lg-6" style="margin: 0 0 15px 0;">
                <span><i class="fa fa-fire-extinguisher"></i></span>
                <input id="addPetColor" type="text" class="form-control" name="color" placeholder="Kleur van uw dier" required value="<?php echo $petColorOld; ?>">
            </div>

            <div class="left-inner-addon form-group col-lg-6" style="margin: 0 0 15px 0;">
                <span><i class="fa fa-map-marker"></i></span>
                <input id="addPetLastSeen" type="text" class="form-control" name="lastSeen" placeholder="Laatste keer gezien in?" required value="<?php echo $petLostPlaceOld; ?>">
            </div>
            <div style="clear:both"></div>
            <?php
            $selected = "selected";
            if($changeID){
                if($petGenderOld == "Mannelijk"){
                    $mannelijk = "selected"; 
                    $selected = ""; 
                    $vrouwelijk = "";
                }else{
                    if($petGenderOld == "Vrouwelijk"){
                        $vrouwelijk = "selected";
                        $selected = ""; 
                        $mannelijk = "";  
                    }
                }

            }
            ?>
            <div class="form-group col-md-6 col-xs-12">
                <div class="col-md-12 col-xs-12 selectContainer ">
                    <select name="geslacht" class="form-control">
                        <option disabled <?php echo $selected; ?> hidden data-icon="glyphicon glyphicon-chevron-right">Kies geslacht</option>
                        <option value="Mannelijk" <?php echo $mannelijk; ?>>Mannelijk</option>
                        <option value="Vrouwelijk" <?php echo $vrouwelijk; ?>>Vrouwelijk</option>
                    </select>
                </div>
            </div>

            <div class="form-group col-md-6 col-xs-12 pull-right">
                <div class="col-md-12 col-xs-12 date">
                    <div class="input-group date" id="dateRangePicker">
                        <input type="text" class="form-control" name="date" placeholder="Vermist sinds?" value="<?php echo $petlostDateOld; ?>"/>
                        <span class="input-group-addon add-on"><span class="glyphicon glyphicon-calendar"></span></span>
                    </div>
                </div>
            </div>
            <div style="clear:both"></div>
            <div class="form-group">
                <div class="col-xs-12 col-md-12">
                    <textarea name="dierDescription" class="form-control" rows="5" required placeholder="Beschrijf hier uw huisdier"><?php echo $petDetailsOld; ?></textarea>
                </div>
            </div> 
            <!-- Ovdje se prikazuju slike kad se radi update -->
            <?php
                if($changeID){
                    echo "<div id=\"oldPhotos\">";
                    $rezOldPhotos = mysqli_query($kon, "SELECT * FROM petsfotos WHERE pet_id = ". $changeID ."");
                    $nrPhotos = mysqli_num_rows($rezOldPhotos);
                    if($nrPhotos > 0){
                        while($redOldPhotos = mysqli_fetch_assoc($rezOldPhotos)){
                            $photoAlt = $redOldPhotos["id"] . "." . $petNameOld;
                            $photoName = $redOldPhotos["name"];
                            $photoId = $redOldPhotos["id"];
                            echo "<div class=\"file-preview-frame\" data-fileindex=\"0\" id=\"oldFoto-". $photoId ."\">
                                    <img class=\"file-preview-image\" style=\"width:auto;height:160px;\" alt=\"". $photoAlt ."\" title=\"". $photoAlt ."\" src=\"images/uploads/pets/". $changeID ."/". $photoName ."\">
                                    <div class=\"file-thumbnail-footer\">
                                        <div class=\"file-footer-caption\" title=\"". $photoName ."\">". $photoName ."</div>
                                        <div class=\"file-actions\">
                                            <div class=\"file-footer-buttons\">
                                                <button class=\"linkDelOldFoto kv-file-remove btn btn-xs btn-danger\" title=\"Verwijder deze foto\" type=\"button\" id=\"btnDelOldFoto-". $photoId ."\">
                                                    <i class=\"glyphicon glyphicon-trash text-danger\" style=\"color:#fff;\"></i> Delete
                                                </button>
                                            </div>
                                        <div class=\"clearfix\"></div>
                                        </div>
                                    </div>
                                </div> ";   
                        }
                    }else{
                        echo "<div style=\"text-align:center;\" class=\"alert alert-warning alert-dismissible\">
                                <button type=\"button\" class=\"close\" data-dismiss=\"alert\" aria-label=\"Close\"><span aria-hidden=\"true\">&times;</span></button>
                                Er zijn geen foto's voor <b>". $petNameOld ."</b> toegevoegd!
                            </div>";    
                    }
                    echo "</div>";
                }
            ?>


            <div style="clear:both"></div>
            <div class="form-group">
                <div class="col-xs-12 col-md-12">
                     <input id="input-700" name="kartik-input-700[]" type="file" multiple class="file-loading" data-show-upload="false" data-show-caption="true">
                     <span class="help-block" style="color:#31708f;margin-top:2px;font-size:12px;">U kan meerdere fotos (max 6) selecteren door op CTRL te blijeven duwen en fotos aan te duiden</span>
                </div>
            </div> 


            <div style="clear:both"></div>

            <div class="form-group pull-right">
                <!-- Button -->
                <!-- Ako nije poslan changeID znaci da nije promjena, tako da imamo dugme za toevoegen -->    
                <?php
                    if(!$_POST["changeID"]){
                ?>                                    
                <div class="col-md-12">
                    <div id="pleaseWaitGif" style="display:none;z-index:99999999;float:left;margin:5px 3px 0 0;"><img src="img/ajax-loader-small.gif" title="Even geduld aub"></div>
                    <button id="btn-add-pet" type="submit" class="btn btn-info"><i class="fa fa-plus-circle"></i> &nbsp Toevoegen</button>
                </div>
                <?php
                    // Ako je poslan changeID znaci da je za update, tako da prikazujemo dugme za update //
                    }else{
                        echo "<div class=\"col-md-6 col-lg-6 col-xs-12\">
                                <div id=\"pleaseWaitGif\" style=\"display:none;z-index:99999999;float:left;margin:5px 3px 0 0;\"><img src=\"img/ajax-loader-small.gif\" title=\"Even geduld aub\"></div>
                                <button id=\"btn-add-pet\" type=\"submit\" class=\"btn btn-success\" data-title=\"Wijzig de gegevens\"><i class=\"fa fa-pencil-square-o\"></i> &nbsp Wijzigen</button>
                            </div>";
                    }
                ?>
            </div>
        </form>
        <?php
            if($_POST["changeID"]){
                echo "<div id=\"cancelBack\" class=\"col-md-6 col-lg-6 col-xs-12\">
                        <button id=\"dataTitle\" class=\"btn btn-danger btn-cancel\" data-title=\"Ga terug\"><i class=\"fa fa fa-ban\"></i> &nbsp Cancel</button>
                    </div>";
            }
        ?> 

 </div>
</div>

dier-toevoegen-submit.php文件是:

<?php
session_start();
include("config.php");
global $kon;
ob_start();
$hiddenID = $_POST["txtHiddenID"];

if(isset($_SESSION["user"]) || isset($_COOKIE["user"])){
    if($hiddenID){
        $petName = addslashes(preg_replace("#[^0-9a-zA-Z ,.\'?!;:\-()\"èéíîçïàçùèûâêôëËÀÇÙÈÛÂÊÔËÄÖÜßäöüßáüÜÉëàçùèûâêôëäöüÈÉÍÎÇÏÀÇÙÈÛÂÊÔËßÄÖÜßÁÜÜÉÑñóÓœŒúÚŸÿóÓñÑòÒìÌãÃęĘąĄšč枊ĐČĆŽ]#i"," ",$_POST["name"]));
        $petBreed = addslashes(preg_replace("#[^0-9a-zA-Z ,.\'?!;:\-()\"èéíîçïàçùèûâêôëËÀÇÙÈÛÂÊÔËÄÖÜßäöüßáüÜÉëàçùèûâêôëäöüÈÉÍÎÇÏÀÇÙÈÛÂÊÔËßÄÖÜßÁÜÜÉÑñóÓœŒúÚŸÿóÓñÑòÒìÌãÃęĘąĄšč枊ĐČĆŽ]#i"," ",$_POST["breed"]));
        $petLostPlace = addslashes(preg_replace("#[^0-9a-zA-Z ,.\'?!;:\-()\"èéíîçïàçùèûâêôëËÀÇÙÈÛÂÊÔËÄÖÜßäöüßáüÜÉëàçùèûâêôëäöüÈÉÍÎÇÏÀÇÙÈÛÂÊÔËßÄÖÜßÁÜÜÉÑñóÓœŒúÚŸÿóÓñÑòÒìÌãÃęĘąĄšč枊ĐČĆŽ]#i"," ",$_POST["lastSeen"]));
        $petColor = addslashes(preg_replace("#[^0-9a-zA-Z ,.\'?!;:\-()\"èéíîçïàçùèûâêôëËÀÇÙÈÛÂÊÔËÄÖÜßäöüßáüÜÉëàçùèûâêôëäöüÈÉÍÎÇÏÀÇÙÈÛÂÊÔËßÄÖÜßÁÜÜÉÑñóÓœŒúÚŸÿóÓñÑòÒìÌãÃęĘąĄšč枊ĐČĆŽ]#i"," ",$_POST["color"]));
        $petGender = $_POST["geslacht"];
        $petLostDate = $_POST["date"];
        $petChangedDate = date("Y/m/d");
        $petDesc = addslashes(preg_replace("#[^0-9a-zA-Z ,.\'?!;:\-()\"èéíîçïàçùèûâêôëËÀÇÙÈÛÂÊÔËÄÖÜßäöüßáüÜÉëàçùèûâêôëäöüÈÉÍÎÇÏÀÇÙÈÛÂÊÔËßÄÖÜßÁÜÜÉÑñóÓœŒúÚŸÿóÓñÑòÒìÌãÃęĘąĄšč枊ĐČĆŽ]#i"," ",$_POST["dierDescription"]));

        //We get the user info from a database with a cookie or session
        if(isset($_SESSION["user"])){
            $session_code = $_SESSION["user"];
        }else{
            if(isset($_COOKIE["user"])){
                $session_code = $_COOKIE["user"];
            }
        }

        //Uzimamo korisnika koji ima trenutnu sesiju
        $rezUser = mysqli_query($kon, "SELECT * FROM korisnici WHERE sessionCode = '" . $session_code . "' LIMIT 1");
        $redUser = mysqli_fetch_assoc($rezUser);
        $idUser = $redUser["id"];

        if(mysqli_query($kon,"UPDATE pets SET 
                               name = '". $petName ."',
                               breed = '". $petBreed ."',
                               lostPlace = '". $petLostPlace ."',
                               color = '". $petColor ."',
                               gender = '". $petGender ."',
                               lostDate = '". $petLostDate ."',
                               details = '". $petDesc ."',
                               changedDate = '". $petChangedDate ."'
                               WHERE id = ". $hiddenID .""
                        )
            ){

                //Slike
                $images_arr = array();
                if(!empty($_FILES['kartik-input-700']['name'][0])){
                    foreach($_FILES['kartik-input-700']['name'] as $key=>$val){
                        $image_name = $_FILES['kartik-input-700']['name'][$key];
                        $tmp_name   = $_FILES['kartik-input-700']['tmp_name'][$key];
                        $size       = $_FILES['kartik-input-700']['size'][$key];
                        $type       = $_FILES['kartik-input-700']['type'][$key];
                        $error      = $_FILES['kartik-input-700']['error'][$key];

                        //Ovdje uzimamo id od zadnje zivotinje koju je dodao user cija je sesija ili cookie aktivan
                        $rezPet = mysqli_query($kon, "SELECT * FROM pets WHERE user_id = ". $idUser ." ORDER BY id DESC LIMIT 1");
                        $redPet = mysqli_fetch_assoc($rezPet);
                        $petId = $redPet["id"];

                        if(!file_exists("images/uploads/pets/". $petId ."/")){
                            mkdir("images/uploads/pets/". $petId ."/",0777);
                        }

                        $target_dir = "images/uploads/pets/". $petId ."/";
                        $target_file = $target_dir.$_FILES['kartik-input-700']['name'][$key];
                        if(move_uploaded_file($_FILES['kartik-input-700']['tmp_name'][$key],$target_file)){
                            $images_arr[] = $target_file;
                            mysqli_query($kon, "INSERT INTO petsfotos VALUES (NULL, '". $type ."','". $image_name ."',". $petId .")");

                            require_once 'ThumbLib.inc.php';

                            $thumb = PhpThumbFactory::create("images/uploads/pets/". $petId ."/". $image_name ."");
                            $thumb->resize(800, 0);
                            $thumb->save("images/uploads/pets/". $petId ."/thumbbig_". $image_name . "");   

                            $thumb->resize(220, 0);
                            $thumb->save("images/uploads/pets/". $petId ."/thumb_". $image_name . "");  

                            $thumb->resize(140, 0);
                            $thumb->save("images/uploads/pets/". $petId ."/thumbsmall_". $image_name . ""); 


                        }else{
                            $noPhotosAdded = "No photos added"; 
                        }
                    }
                }


                if (empty($images_arr)) {
                    $noPhotosSelected = "No photos selected";
                }

                echo json_encode(array(
                    'result' => "<span style=\"font-size:16px;font_weight:bold;\"><i class=\"fa fa-thumbs-o-up\"></i>Uw huisdier is succesvol gewijzigd.</span><br/><br/> Wij hopen dat <b>". $petName ."</b> zo snel mogelijk terug naar huis zal komen!",
                    'status' => "Updated",
                    'noPhotosAdded' => $noPhotosAdded,
                    'noPhotosSelected' => $noPhotosSelected
                ));

            }else{
                echo json_encode(array(
                    'result' => "Uw huisdier is niet gewijzigd.",
                    'status' => "NotUpdated"
                ));
            }

    }else{
        $petName = addslashes(preg_replace("#[^0-9a-zA-Z ,.\'?!;:\-()\"èéíîçïàçùèûâêôëËÀÇÙÈÛÂÊÔËÄÖÜßäöüßáüÜÉëàçùèûâêôëäöüÈÉÍÎÇÏÀÇÙÈÛÂÊÔËßÄÖÜßÁÜÜÉÑñóÓœŒúÚŸÿóÓñÑòÒìÌãÃęĘąĄšč枊ĐČĆŽ]#i"," ",$_POST["name"]));
        $petBreed = addslashes(preg_replace("#[^0-9a-zA-Z ,.\'?!;:\-()\"èéíîçïàçùèûâêôëËÀÇÙÈÛÂÊÔËÄÖÜßäöüßáüÜÉëàçùèûâêôëäöüÈÉÍÎÇÏÀÇÙÈÛÂÊÔËßÄÖÜßÁÜÜÉÑñóÓœŒúÚŸÿóÓñÑòÒìÌãÃęĘąĄšč枊ĐČĆŽ]#i"," ",$_POST["breed"]));
        $petLostPlace = addslashes(preg_replace("#[^0-9a-zA-Z ,.\'?!;:\-()\"èéíîçïàçùèûâêôëËÀÇÙÈÛÂÊÔËÄÖÜßäöüßáüÜÉëàçùèûâêôëäöüÈÉÍÎÇÏÀÇÙÈÛÂÊÔËßÄÖÜßÁÜÜÉÑñóÓœŒúÚŸÿóÓñÑòÒìÌãÃęĘąĄšč枊ĐČĆŽ]#i"," ",$_POST["lastSeen"]));
        $petColor = addslashes(preg_replace("#[^0-9a-zA-Z ,.\'?!;:\-()\"èéíîçïàçùèûâêôëËÀÇÙÈÛÂÊÔËÄÖÜßäöüßáüÜÉëàçùèûâêôëäöüÈÉÍÎÇÏÀÇÙÈÛÂÊÔËßÄÖÜßÁÜÜÉÑñóÓœŒúÚŸÿóÓñÑòÒìÌãÃęĘąĄšč枊ĐČĆŽ]#i"," ",$_POST["color"]));
        $petGender = $_POST["geslacht"];
        $petLostDate = $_POST["date"];
        $petFoundDate = NULL;
        $petChangedDate = NULL;
        $petDesc = addslashes(preg_replace("#[^0-9a-zA-Z ,.\'?!;:\-()\"èéíîçïàçùèûâêôëËÀÇÙÈÛÂÊÔËÄÖÜßäöüßáüÜÉëàçùèûâêôëäöüÈÉÍÎÇÏÀÇÙÈÛÂÊÔËßÄÖÜßÁÜÜÉÑñóÓœŒúÚŸÿóÓñÑòÒìÌãÃęĘąĄšč枊ĐČĆŽ]#i"," ",$_POST["dierDescription"]));
        $found = 0;
        $addedDate = date("Y/m/d");
        $views = 0;
        $paid = 0;



        //We get the user info from a database with a cookie or session
        if(isset($_SESSION["user"])){
            $session_code = $_SESSION["user"];
        }else{
            if(isset($_COOKIE["user"])){
                $session_code = $_COOKIE["user"];
            }
        }

        //Uzimamo korisnika koji ima trenutnu sesiju
        $rezUser = mysqli_query($kon, "SELECT * FROM korisnici WHERE sessionCode = '" . $session_code . "' LIMIT 1");
        $redUser = mysqli_fetch_assoc($rezUser);
        $idUser = $redUser["id"];

        if(mysqli_query($kon,"INSERT INTO pets VALUES (
                               NULL,
                               '". $petName ."',
                               '". $petBreed ."',
                               '". $petLostPlace ."',
                               '". $petColor ."',
                               '". $petGender ."',
                               '". $petLostDate ."',
                               '". $petFoundDate ."',
                               '". $petDesc ."',
                               ". $found .",
                               '". $addedDate ."',
                               '". $petChangedDate ."',
                               ". $idUser .",
                               ". $views .",
                               ". $paid .")"
                        ))
            {

                //Slike
                $images_arr = array();
                if(!empty($_FILES['kartik-input-700']['name'][0])){
                    foreach($_FILES['kartik-input-700']['name'] as $key=>$val){
                        $image_name = $_FILES['kartik-input-700']['name'][$key];
                        $tmp_name   = $_FILES['kartik-input-700']['tmp_name'][$key];
                        $size       = $_FILES['kartik-input-700']['size'][$key];
                        $type       = $_FILES['kartik-input-700']['type'][$key];
                        $error      = $_FILES['kartik-input-700']['error'][$key];

                        //Ovdje uzimamo id od zadnje zivotinje koju je dodao user cija je sesija ili cookie aktivan
                        $rezPet = mysqli_query($kon, "SELECT * FROM pets WHERE user_id = ". $idUser ." ORDER BY id DESC LIMIT 1");
                        $redPet = mysqli_fetch_assoc($rezPet);
                        $petId = $redPet["id"];

                        if(!file_exists("images/uploads/pets/". $petId ."/")){
                            mkdir("images/uploads/pets/". $petId ."/",0777);
                        }

                        $target_dir = "images/uploads/pets/". $petId ."/";
                        $target_file = $target_dir.$_FILES['kartik-input-700']['name'][$key];
                        if(move_uploaded_file($_FILES['kartik-input-700']['tmp_name'][$key],$target_file)){
                            $images_arr[] = $target_file;
                            mysqli_query($kon, "INSERT INTO petsfotos VALUES (NULL, '". $type ."','". $image_name ."',". $petId .")");

                            require_once 'ThumbLib.inc.php';

                            $thumb = PhpThumbFactory::create("images/uploads/pets/". $petId ."/". $image_name ."");
                            $thumb->resize(800, 0);
                            $thumb->save("images/uploads/pets/". $petId ."/thumbbig_". $image_name . "");   

                            $thumb->resize(220, 0);
                            $thumb->save("images/uploads/pets/". $petId ."/thumb_". $image_name . "");  

                            $thumb->resize(140, 0);
                            $thumb->save("images/uploads/pets/". $petId ."/thumbsmall_". $image_name . ""); 


                        }else{
                            $noPhotosAdded = "No photos added"; 
                        }
                    }
                }


                if (empty($images_arr)) {
                    $noPhotosSelected = "No photos selected";
                }

                $rezPets = mysqli_query($kon, "SELECT * FROM pets");
                $nrPets = mysqli_num_rows($rezPets);

                echo json_encode(array(
                    'result' => "<span style=\"font-size:16px;font_weight:bold;\"><i class=\"fa fa-thumbs-o-up\"></i>Uw huisdier is toegevoegd.</span><br/><br/> Wij hopen dat <b>". $petName ."</b> zo snel mogelijk terug naar huis zal komen!",
                    'status' => "Added",
                    'noPhotosAdded' => $noPhotosAdded,
                    'noPhotosSelected' => $noPhotosSelected,
                    'nrPets' => $nrPets
                ));

            }else{
                echo json_encode(array(
                    'result' => "Uw huisdier is niet toegevoegd.",
                    'status' => "NotAdded"
                ));
            }
    }


}else{
    header("Location:index.php");
}
ob_flush();

&GT;

有什么想法吗?感谢。

0 个答案:

没有答案