PHP - Simple Upload Files Using PDO & Ajax

In this tutorial we will create a Simple Upload Files using PDO & Ajax PHP is a server-side scripting language designed primarily for web development. PDO stands for PHP Data Objects. It is a lean and consistent way to access databases. This means developers can write portable code much easier. It is mostly used by a newly coders for its user friendly environment. So Let's do the coding.

Getting started:

First you have to download & install XAMPP or any local server that run PHP scripts. Here's the link for XAMPP server https://www.apachefriends.org/index.html. And this is the link for the jquery that i used in this tutorial https://jquery.com/. Lastly, this is the link for the bootstrap that i used for the layout design https://getbootstrap.com/.

Creating the database connection

Open your any kind of text editor(notepad++, etc..). Then just copy/paste the code below then name it conn.php.
  1. <?php
  2.         $conn = new PDO( 'mysql:host=localhost;dbname=db_file', 'root', '');
  3.         if(!$conn){
  4.                 die("Fatal Error: Connection Failed!");
  5.         }
  6. ?>

Creating The Interface

This is where we will create a simple form for our application. To create the forms simply copy and write it into you text editor, then save it as index.php.
  1. <!DOCTYPE html>
  2. <html lang="en">
  3.         <head>
  4.                 <meta charset="UTF-8" name="viewport" content="width=device-width, initial-scale=1"/>
  5.                 <link rel="stylesheet" type="text/css" href="css/bootstrap.css"/>
  6.         </head>
  7. <body>
  8.         <nav class="navbar navbar-default">
  9.                 <div class="container-fluid">
  10.                         <a class="navbar-brand" href="https://sourcecodester.com">Sourcecodester</a>
  11.                 </div>
  12.         </nav>
  13.         <div class="col-md-3"></div>
  14.         <div class="col-md-6 well">
  15.                 <h3 class="text-primary">PHP - Simple Upload Files Using PDO & Ajax</h3>
  16.                 <hr style="border-top:1px dotted #ccc;"/>
  17.                 <form class="form-inline" method="POST">
  18.                         <label><input type="file" id="file" class="form-control"/></label>
  19.                         <button type="button" class="btn btn-primary" id="upload"><span class="glyphicon glyphicon-upload"></span> Upload</button>
  20.                         <br /><br />
  21.                         <div id="result" style="display:none;"></div>
  22.                 </form>
  23.                 <div class="table-responsive">
  24.                         <table class="table table-bordered">
  25.                                 <thead class="alert-info">
  26.                                         <tr>
  27.                                                 <th>File Name</th>
  28.                                                 <th>Location</th>
  29.                                         </tr>
  30.                                 </thead>
  31.                                 <tbody id="data" style="background-color:#fff;"></tbody>
  32.                         </table>
  33.                 </div>
  34.         </div>
  35. <script src="js/jquery-3.2.1.min.js"></script> 
  36. <script src="js/script.js"></script>
  37. </body>
  38. </html>

Creating the Main Function

This code contains the main function of the application. This code will upload the file using ajax request to prevent the web browser from refreshing. To do this just copy and write these block of codes as shown below inside the text editor, then save it as show below. data.php
  1. <?php
  2.         require 'conn.php';
  3.         $query = $conn->prepare("SELECT * FROM `file` ORDER BY `filename` ASC");
  4.         $query->execute();
  5.         while($fetch = $query->fetch()){
  6. ?>
  7. <tr>
  8.         <td><?php echo $fetch['filename']?></td>
  9.         <td><?php echo $fetch['location']?></td>
  10. </tr>
  11. <?php
  12.         }
  13. ?>
upload.php
  1. <?php
  2.         require_once 'conn.php';
  3.  
  4.  
  5.         try{
  6.                 $file_name = $_FILES['file']['name'];
  7.                 $file_temp = $_FILES['file']['tmp_name'];
  8.                 $path = "upload/".$file_name;
  9.                 $exp = explode(".", $_FILES['file']['name']);
  10.                 $name = $exp[0];
  11.                
  12.                 if(move_uploaded_file($file_temp, $path)){
  13.                         $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
  14.                         $sql = "INSERT INTO `file` (`filename`, `location`) VALUES ('$name', '$path')";
  15.                         $conn->exec($sql);
  16.                 }
  17.                
  18.         }catch(PDOException $e){
  19.                 echo $e->getMessage();
  20.         }
  21.  
  22.         $conn = null;
  23.        
  24.         echo "success";
  25. ?>
script.js Save this file inside the js directory.
  1. $(document).ready(function(){
  2.        
  3.         display_data();
  4.        
  5.         function display_data(){
  6.                 $.ajax({
  7.                         url: 'data.php',
  8.                         type: 'POST',
  9.                         data: {res: 1},
  10.                         success: function(data){
  11.                                 $('#data').html(data);
  12.                         }
  13.                 });
  14.         }
  15.        
  16.         $('#upload').on('click', function(){
  17.                 var file = $('#file');
  18.                 var file_length = file[0].files.length;
  19.                 var file_data = file.prop('files')[0];
  20.                 $('#result').css('display', '');
  21.                 if(file_length > 0){
  22.                         var form_data = new FormData();
  23.                         form_data.append('file', file_data);
  24.                         $.ajax({
  25.                                 url: 'upload.php',
  26.                                 type: 'POST',
  27.                                 processData: false,
  28.                                 contentType: false,
  29.                                 data: form_data,
  30.                                 success: function(data){
  31.                                         if(data == "success"){
  32.                                                 $("#result").attr('class', 'alert alert-success');
  33.                                                 $("#result").html("File uploaded");
  34.                                                 display_data();
  35.                                         }
  36.                                 }
  37.                         });
  38.                 }else{
  39.                         $("#result").attr('class', 'alert alert-danger');
  40.                         $("#result").html("Please select a file first");
  41.                 }
  42.                
  43.         });
  44. });
There you have it we successfully created a Simple Upload Files using PDO & Ajax. I hope that this simple tutorial help you to what you are looking for. For more updates and tutorials just kindly visit this site. Enjoy Coding!!!

Add new comment