How to upload file using php/ajax and save into database

How to upload a single file using PHP and save it into database

Single file upload system

Create a formupload.php file

<head>
 <script src="formajax.js"></script>
</head>
<form id="codelizar_form" method="post" enctype="multipart/form-data">
  <div class="row">
    <div class="form-group col-md-3">
     <label for="user_name" class="heading-2">User name * </label>
     <input type="text" name="user_name" id="user_name" class="form-control" placeholder="Enter user name" required="required">
    </div>
    <div class="col-md-3">
        <label for="file_img">Choose Image *</label>
	<input type="file" class="form-control-file" id="file_img" name="file_img" required="required">
   </div>
   <button type="submit" id="save_form_btn" class="btn btn-primary">Save&nbsp;<i class="far fa-save"></i></button>
  </div>
</form>

Create a formajax.js file

$("#codelizar_form").on('submit', function(e){
        e.preventDefault();
        
        $.ajax({
          method: 'POST',
          url: 'user-ajaxhandler.php',
          data:  $('#codelizar_form').serialize(),
                contentType: false,
                cache: false,
                processData:false,      
          success: function( response_userdata ) {
            $('#codelizar_form')[0].reset(); // form reset
            alert("Successfully Uploaded);
            location.reload("true");
          }
        });
      });

Create user-ajaxhandler.php file

/* User registration */
	if( isset( $_REQUEST['user_name'] ) ) {
		$user_name = $_REQUEST['user_name'];
		$uploadedIMG  = '';

		if( !empty($_FILES['file_img']['name'] ) ) {        
			if( !empty( $_FILES["file_img"]["type"] ) ) {
				$fileName = time().'_'.$_FILES['file_img']['name'];
				$valid_extensions = array("jpeg", "jpg", "png");
				$temporary = explode(".", $_FILES["file_img"]["name"]);
				$file_extension = end($temporary);
				if((($_FILES["file_img"]["type"] == "image/png") || ($_FILES["file_img"]["type"] == "image/jpg") || ($_FILES["file_img"]["type"] == "image/jpeg")) && in_array($file_extension, $valid_extensions)){
					$sourcePath = $_FILES['file_img']['tmp_name'];
					$targetPath = "../../assets/img/user_img/".$fileName; 
					if(move_uploaded_file($sourcePath,$targetPath)){
						$uploadedIMG  = $fileName;
					}
				}
			}
		}

   $query = "INSERT INTO `user_tbl`(`id`, `user_name`, `user_img`) VALUES ('','$user_name', '$uploadedIMG')";
   mysqli_query($conn,$query);	
}

 

Leave a Reply

Your email address will not be published. Required fields are marked *