PHP - Simple Upload Files Using PDO & Ajax

Submitted by: 
Language: 
Visitors have accessed this post 297 times.

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="<a href="https://sourcecodester.com">Sourcecodester</a>
  11. " rel="nofollow">https://sourcecodester.com">Sourcecodester</a>
  12. </a> </div>
  13. </nav>
  14. <div class="col-md-3"></div>
  15. <div class="col-md-6 well">
  16. <h3 class="text-primary">PHP - Simple Upload Files Using PDO & Ajax</h3>
  17. <hr style="border-top:1px dotted #ccc;"/>
  18. <form class="form-inline" method="POST">
  19. <label><input type="file" id="file" class="form-control"/></label>
  20. <button type="button" class="btn btn-primary" id="upload"><span class="glyphicon glyphicon-upload"></span> Upload</button>
  21. <br /><br />
  22. <div id="result" style="display:none;"></div>
  23. </form>
  24. <div class="table-responsive">
  25. <table class="table table-bordered">
  26. <thead class="alert-info">
  27. <tr>
  28. <th>File Name</th>
  29. <th>Location</th>
  30. </tr>
  31. </thead>
  32. <tbody id="data" style="background-color:#fff;"></tbody>
  33. </table>
  34. </div>
  35. </div>
  36. <script src="js/jquery-3.2.1.min.js"></script>
  37. <script src="js/script.js"></script>
  38. </body>
  39. </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

Filtered HTML

  • Web page addresses and e-mail addresses turn into links automatically.
  • You may insert videos with [video:URL]
  • Allowed HTML tags: <a> <em> <strong> <cite> <blockquote> <code> <ul> <ol> <li> <dl> <dt> <dd> <table> <tr> <td> <th> <img> <h1> <h2> <h3> <iframe> [video]
  • You can enable syntax highlighting of source code with the following tags: <code>, <blockcode>, <asp>, <c>, <cpp>, <csharp>, <css>, <html4strict>, <java>, <javascript>, <mysql>, <php>, <python>, <sql>, <vb>, <vbnet>. The supported tag styles are: <foo>, [foo].
  • Lines and paragraphs break automatically.

Plain text

  • No HTML tags allowed.
  • Lines and paragraphs break automatically.
CAPTCHA
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.