Upload Multiple Pdf Files to the Database Using Pdo - Php

This is a comprehensive PHP 8 Multiple Files and Images uploading tutorial, acquire to store image files in the MySQL database forth with some necessary file uploading validation.

File upload in PHP is the most common feature that about every PHP programmer has to build. As we tin can know, file uploading functionality is required in nearly every spider web application. Be it Instagram, Twitter, Facebook or Tumblr a user can't alive without uploading files nowadays.

In this tutorial, nosotros will acquire how to upload single or multiple files or images in PHP 8 and how to salve the images in MySQL database. Nosotros volition also comprehend the necessary file uploading validation using the PHP methods and API.

Unremarkably, a user tends to upload a unmarried image and shop the image on the database using the file name. This mode, nosotros can besides fetch the prototype or file from the database using the file name. Sometimes, based on some specific requirements, we have to upload Multiple images or files on the server.

Table of Contents

  1. Tutorial Objective
  2. Project Files Structure
  3. Table Configuration in Database
  4. Connect PHP Project with MySQL
  5. Create File Upload Form
  6. Display Multiple Files Preview
  7. Upload Multiple Files in PHP with Validation
  8. Decision

Tutorial Objective

By the finish of this tutorial, you will be able to sympathise the following concepts:

  • Create an HTML form to select multiple images and files.
  • Display multiple images preview earlier sending to server.
  • Implement necessary validation before uploading.
  • Save files in the local directory and shop the uploaded file path in the database.

Project Files Structure

We are following the given below files and folder construction to upload multiple files in PHP viii.

                                  \-- php-multiple-file-upload                  |-- config                  |--- database.php                  |-- uploads                  |--- image-1                  |--- image-2                  |--- image-3                  |-- file-upload.php                  |-- index.php              

Table Configuration in Database

You can apply MAMP or XAMPP to create database and table for multiple file uploading in PHP.

Create database `database_name`.

Create `table_name` inside the database.

Run the following SQL script from the PHPMyAdmin console to create user tables, and it will have an id, images, and data_time values in the MySQL database.

                                  CREATE                  TABLE                  `                  user                  `                  (                  `id`                  int                  (                  xi                  )                  Not                  NULL                  ,                  `images`                  varchar                  (                  255                  )                  NOT                  NULL                  ,                  `date_time`                  datetime                  Not                  Zilch                  )                  ENGINE                  =                  InnoDB                  DEFAULT                  CHARSET                  =utf8;                              

Connect PHP Project with MySQL

To brand the connection between the database and PHP project, we defined the database connectedness with the PDO approach and kept the db configuration in the config/database.php file.

                                                      <?php                    $hostname                    =                    "localhost"                    ;                    $username                    =                    "root"                    ;                    $password                    =                    ""                    ;                    attempt                    {                    $conn                    =                    new                    PDO                    (                    "mysql:host=                        $hostname                      ;dbname=php_crud"                    ,                    $username                    ,                    $countersign                    )                    ;                    // set the PDO mistake way to exception                    $conn                    -                    >                    setAttribute                    (                    PDO                    :                    :                    ATTR_ERRMODE                    ,                    PDO                    :                    :                    ERRMODE_EXCEPTION                    )                    ;                    //echo "Database connected successfully";                    }                    catch                    (PDOException                    $e                    )                    {                    echo                    "Database connexion failed: "                    .                    $e                    -                    >                    getMessage                    (                    )                    ;                    }                    ?>                                                

Create File Upload Class with HTML and Bootstrap iv

To create the file upload form we are using Bootstrap four, add the Bootstrap CDN link in between the head tag.

                                                                            <link                    rel                                          =                      "stylesheet"                                        href                                          =                      "https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css"                                        >                                                

Create a simple file upload form using HTML course tag, the class tag must incorporate the method="mail service" and enctype="multipart/form-data" tags.

To make it collaborate with PHP APIs, do define the proper noun="fileUpload[]" tag with an input form field. Past default, the HTML file field allows a single file to upload. Pass the multiple tag with a file input field to cull multiple files at in one case.

                                                                            <course                    action                                          =                      "                      "                                        method                                          =                      "post"                                        enctype                                          =                      "multipart/class-data"                                        class                                          =                      "mb-3"                                        >                                                                              <div                    class                                          =                      "custom-file"                                        >                                                                              <input                    blazon                                          =                      "file"                                        name                                          =                      "fileUpload[]"                                        class                                          =                      "custom-file-input"                                        id                                          =                      "chooseFile"                                        multiple                    >                                                                              <label                    course                                          =                      "custom-file-label"                                        for                                          =                      "chooseFile"                                        >                  Select file                                          </characterization                    >                                                                              </div                    >                                                                              <push                    type                                          =                      "submit"                                        proper noun                                          =                      "submit"                                        class                                          =                      "btn btn-primary btn-block mt-4"                                        >                                    Upload Files                                                            </push button                    >                                                                              </form                    >                                                

Brandish Multiple Files Preview

A user must know which files he is going to put on the server, create a html div within the files upload form.

                                                                            <div                    course                                          =                      "imgGallery"                                        >                                    <!-- paradigm preview -->                                                            </div                    >                                                

We need to place the jQuery link in the footer and also place the following JavaScript code that shows the preview of all the user selected files.

                                  <script src=                  "https://code.jquery.com/jquery-3.v.ane.slim.min.js"                  >                  <                  /script>                  <script>                  $                  (                  office                  (                  )                  {                  // Multiple images preview with JavaScript                  var                  multiImgPreview                  =                  part                  (                  input,                    imgPreviewPlaceholder                  )                  {                  if                  (input.files)                  {                  var                  filesAmount                  =                  input.files.length;                  for                  (i                  =                  0                  ;                  i                  <                  filesAmount;                  i++                  )                  {                  var                  reader                  =                  new                  FileReader                  (                  )                  ;                  reader.                  onload                  =                  function                  (                  consequence                  )                  {                  $                  ($.                  parseHTML                  (                  '<img>'                  )                  )                  .                  attr                  (                  'src'                  ,                  issue.target.upshot)                  .                  appendTo                  (imgPreviewPlaceholder)                  ;                  }                  reader.                  readAsDataURL                  (input.files[i]                  )                  ;                  }                  }                  }                  ;                  $                  (                  '#chooseFile'                  )                  .                  on                  (                  'change'                  ,                  function                  (                  )                  {                  multiImgPreview                  (                  this                  ,                  'div.imgGallery'                  )                  ;                  }                  )                  ;                  }                  )                  ;                  <                  /script>                              

Display Multiple Files Preview in PHP 8

Upload Multiple Files in PHP viii with Validation

We define the multiple file uploading code in the file-upload.php file and alarm the user about the file upload activity.

                                                      <?php                    // Database                    include                    'config/database.php'                    ;                    if                    (                    isset                    (                    $_POST                    [                    'submit'                    ]                    )                    )                    {                    $uploadsDir                    =                    "uploads/"                    ;                    $allowedFileType                    =                    assortment                    (                    'jpg'                    ,                    'png'                    ,                    'jpeg'                    )                    ;                    // Velidate if files exist                    if                    (                    !                    empty                    (                    array_filter                    (                    $_FILES                    [                    'fileUpload'                    ]                    [                    'name'                    ]                    )                    )                    )                    {                    // Loop through file items                    foreach                    (                    $_FILES                    [                    'fileUpload'                    ]                    [                    'name'                    ]                    as                    $id                    =                    >                    $val                    )                    {                    // Get files upload path                    $fileName                    =                    $_FILES                    [                    'fileUpload'                    ]                    [                    'name'                    ]                    [                    $id                    ]                    ;                    $tempLocation                    =                    $_FILES                    [                    'fileUpload'                    ]                    [                    'tmp_name'                    ]                    [                    $id                    ]                    ;                    $targetFilePath                    =                    $uploadsDir                    .                    $fileName                    ;                    $fileType                    =                    strtolower                    (                    pathinfo                    (                    $targetFilePath                    ,                    PATHINFO_EXTENSION                    )                    )                    ;                    $uploadDate                    =                    engagement                    (                    'Y-m-d H:i:s'                    )                    ;                    $uploadOk                    =                    1                    ;                    if                    (                    in_array                    (                    $fileType                    ,                    $allowedFileType                    )                    )                    {                    if                    (                    move_uploaded_file                    (                    $tempLocation                    ,                    $targetFilePath                    )                    )                    {                    $sqlVal                    =                    "('"                    .                    $fileName                    .                    "', '"                    .                    $uploadDate                    .                    "')"                    ;                    }                    else                    {                    $response                    =                    array                    (                    "status"                    =                    >                    "alert-danger"                    ,                    "bulletin"                    =                    >                    "File coud not be uploaded."                    )                    ;                    }                    }                    else                    {                    $response                    =                    array                    (                    "status"                    =                    >                    "alert-danger"                    ,                    "message"                    =                    >                    "Only .jpg, .jpeg and .png file formats allowed."                    )                    ;                    }                    // Add into MySQL database                    if                    (                    !                    empty                    (                    $sqlVal                    )                    )                    {                    $insert                    =                    $conn                    -                    >                    query                    (                    "INSERT INTO user (images, date_time) VALUES                                              $sqlVal                      "                    )                    ;                    if                    (                    $insert                    )                    {                    $response                    =                    array                    (                    "status"                    =                    >                    "alert-success"                    ,                    "bulletin"                    =                    >                    "Files successfully uploaded."                    )                    ;                    }                    else                    {                    $response                    =                    array                    (                    "status"                    =                    >                    "alert-danger"                    ,                    "bulletin"                    =                    >                    "Files coudn't exist uploaded due to database error."                    )                    ;                    }                    }                    }                    }                    else                    {                    // Mistake                    $response                    =                    array                    (                    "status"                    =                    >                    "alert-danger"                    ,                    "message"                    =                    >                    "Please select a file to upload."                    )                    ;                    }                    }                    ?>                                                

Add the database connection file to run the SQL query to make the interaction with the database.

Add the validation to brand sure whether the images are selected, and the correct file blazon is chosen, and using the SQL script, insert the files into the database.

If files pass the higher up validation, and then move all the files in the uploads directory with the help of the move_uploaded_file() method and store the images' location path in the database.

Next, include the file-upload.php file in the form template. It allows users to select the multiple files using PHP eight and MySQL.

                                  <?php include("file-upload.php"); ?>                                      <!                    doctype                    html                    >                                                                              <html                    lang                                          =                      "en"                                        >                                                                              <head                    >                                                                              <meta                    charset                                          =                      "utf-viii"                                        >                                                                              <meta                    name                                          =                      "viewport"                                        content                                          =                      "width=device-width, initial-scale=1, shrink-to-fit=no"                                        >                                                                              <link                    rel                                          =                      "stylesheet"                                        href                                          =                      "https://stackpath.bootstrapcdn.com/bootstrap/4.five.0/css/bootstrap.min.css"                                        >                                                                              <title                    >                  PHP 8 Upload Multiple Files Case                                          </championship                    >                                                                              <way                    >                                    .container {       max-width: 450px;     }     .imgGallery img {       padding: 8px;       max-width: 100px;     }                                                            </style                    >                                                                              </head                    >                                                                              <body                    >                                                                              <div                    class                                          =                      "container mt-5"                                        >                                                                              <form                    action                                          =                      "                      "                                        method                                          =                      "post"                                        enctype                                          =                      "multipart/form-data"                                        class                                          =                      "mb-3"                                        >                                                                              <h3                    course                                          =                      "text-center mb-five"                                        >                  Upload Multiple Images in PHP 8                                          </h3                    >                                                                              <div                    grade                                          =                      "user-image mb-three text-center"                                        >                                                                              <div                    form                                          =                      "imgGallery"                                        >                                    <!-- Image preview -->                                                            </div                    >                                                                              </div                    >                                                                              <div                    class                                          =                      "custom-file"                                        >                                                                              <input                    type                                          =                      "file"                                        name                                          =                      "fileUpload[]"                                        class                                          =                      "custom-file-input"                                        id                                          =                      "chooseFile"                                        multiple                    >                                                                              <label                    form                                          =                      "custom-file-label"                                        for                                          =                      "chooseFile"                                        >                  Select file                                          </characterization                    >                                                                              </div                    >                                                                              <button                    blazon                                          =                      "submit"                                        name                                          =                      "submit"                                        course                                          =                      "btn btn-primary btn-block mt-four"                                        >                                    Upload Files                                                            </push                    >                                                                              </form                    >                                    <!-- Display response messages -->                  <?php if(!empty($response)) {?>                                                            <div                    form                                          =                      "warning <?php echo $response["                                        status"];                    ?                    >                  ">                  <?php echo $response["message"]; ?>                                                            </div                    >                                    <?php }?>                                                            </div                    >                                    <!-- jQuery -->                                                            <script                    src                                          =                      "https://lawmaking.jquery.com/jquery-3.v.1.slim.min.js"                                        >                                                                                                                  </script                    >                                                                              <script                    >                                                                              $                      (                      function                      (                      )                      {                      // Multiple images preview with JavaScript                      var                      multiImgPreview                      =                      role                      (                      input,                        imgPreviewPlaceholder                      )                      {                      if                      (input.files)                      {                      var                      filesAmount                      =                      input.files.length;                      for                      (i                      =                      0                      ;                      i                      <                      filesAmount;                      i++                      )                      {                      var                      reader                      =                      new                      FileReader                      (                      )                      ;                      reader.                      onload                      =                      function                      (                      event                      )                      {                      $                      ($.                      parseHTML                      (                      '<img>'                      )                      )                      .                      attr                      (                      'src'                      ,                      event.target.issue)                      .                      appendTo                      (imgPreviewPlaceholder)                      ;                      }                      reader.                      readAsDataURL                      (input.files[i]                      )                      ;                      }                      }                      }                      ;                      $                      (                      '#chooseFile'                      )                      .                      on                      (                      'change'                      ,                      function                      (                      )                      {                      multiImgPreview                      (                      this                      ,                      'div.imgGallery'                      )                      ;                      }                      )                      ;                      }                      )                      ;                                                                                                  </script                    >                                                                              </body                    >                                                                              </html                    >                                                

Conclusion

Finally, multiple images Upload in PHP with MySQL Database tutorial is over. We learned to implement validation for multiple files upload component in PHP.

I assume you loved this tutorial, and you lot can besides notice the full code of this tutorial on GitHub.

shirleyopocone44.blogspot.com

Source: https://www.positronx.io/php-multiple-files-images-upload-in-mysql-database/

0 Response to "Upload Multiple Pdf Files to the Database Using Pdo - Php"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel