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

 <script src="formajax.js"></script>
<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 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">
   <button type="submit" id="save_form_btn" class="btn btn-primary">Save&nbsp;<i class="far fa-save"></i></button>

Create a formajax.js file

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

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; 
						$uploadedIMG  = $fileName;

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


Leave a Reply

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