0

How can I upload the image and save the image address in the mysql ? 1.I want to upload the image with AJAX 2.And the image address will be stored in the mysql with pdo This is my code:

$(document).ready(function(){
    $("#usredit").click(function(){
        var name = $("#name").val();
        var email = $("#email").val();
        var file = $("#file").val();
        var image = $("#image").val();
        var id = $("#id").val();
        var send = true;
        $.post("set-ajax.php",{name:name,email:email,file:file,image:image,id:id,send:send},function(data){
                    $("#editres").html(data);
        });
    });
});

ajax.php

if(isset($_POST['send'])){
    if(empty($_POST['name']) || empty($_POST['email'])){
        echo '<div class="alert alert-warning">Fill empty fields</div>';
            }else{
                if(isset($_POST['file'])){
                    $file = $_POST['file'];
                    $tmp = $_FILES['file']["tmp_name"];
                    $name = $_FILES['file']['name'];
                    $type = $_FILES['file']['type'];
                    if (is_uploaded_file($tmp)){
                        $ext = array("image/jpg","image/png","image/jpeg");
                        if (in_array($type,$ext)){
                            $filename = md5($name.microtime()).substr($name,-5,5);
                        if(move_uploaded_file($tmp,"user/img".$filename)){
                            echo '<div class="alert alert-success">Upload done</div>';
                        }else{
                                echo '<div class="alert alert-warning">Upload failed</div>';
                            }
                        }else{
                            echo '<div class="alert alert-warning">Unrelated file</div>';
                        }
                    }
                }
                $name = $_POST['name'];
                $email = $_POST['email'];
                $image = $_POST['image'];
                $id = $_POST['id'];
                $resualt = $User->UpdateUserProfile($name,$email,$image,$id);
                if($resualt ){
                    echo '<div class="alert alert-success">Edit done</div>';
                }else{
                    echo '<div class="alert alert-warning">Edit failed</div>';
                }
            }
behi
  • 73
  • 8

1 Answers1

0

Assuming, you were able to upload image to user/img folder. Then, create a method which will update/insert details of uploaded image. And call that method by passing image name (since, folder path will be common for all )

      if(move_uploaded_file($tmp,"user/img".$filename)){
            // update/insert table with folder location.
            // call the method here             
           echo '<div class="alert alert-success">Upload done</div>';
        }
Ravi
  • 30,829
  • 42
  • 119
  • 173