article

Tuesday, June 7, 2022

PHP Mysql PDO Image Upload and Insert with validation and preview

PHP Mysql PDO Image Upload and Insert with validation and preview

CREATE TABLE `user` (
  `id` int(11) NOT NULL,
  `image` varchar(255) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

ALTER TABLE `user`
  ADD PRIMARY KEY (`id`);

ALTER TABLE `user`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=1;
  
Bootstrap 5
https://getbootstrap.com/docs/5.0/getting-started/introduction/
https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css
Database configuration

config.php
//config.php
<?php
    $hostname = "localhost";
    $username = "root";
    $password = "";
 
    try {
        $conn = new PDO("mysql:host=$hostname;dbname=devprojectdb", $username, $password);
        // set the PDO error mode to exception
        $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        //echo "Database connected successfully";
    } catch(PDOException $e) {
        echo "Database connection failed: " . $e->getMessage();
    }
?>
Main Page
fileupload.php
//fileupload.php
<!doctype html>
<html lang="en">
<head>
    <title>PHP Mysql PDO Image Upload and Insert with validation and preview</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css">
</head>
<body>
<?php include("save.php"); ?>
    <div class="container mt-5">
        <div class="row">
            <div class="col-md-8 offset-2">
                <div class="card">
                    <div class="card-header">
                        <h3 class="text-center">PHP Mysql PDO Image Upload and Insert with validation and preview</h3>
                    </div>
                    <div class="card-body">
                        <!-- response messages -->
                        <?php if(!empty($resMessage)) {?>
                            <div class="alert <?php echo $resMessage['status']?>">
                                <?php echo $resMessage['message']?>
                            </div>
                        <?php }?>
                        <form action="" method="post" enctype="multipart/form-data" class="mb-3">
                            <div class="user-image mb-3 text-center">
                                <div style="width: 100px; height: 100px; overflow: hidden; background: #cccccc; margin: 0 auto">
                                    <img src="..." class="figure-img img-fluid rounded" id="imgPlaceholder" alt="">
                                </div>
                            </div>
                            <div class="custom-file">
								<div class="input-group mb-3">
								  <input type="file" name="fileUpload" class="form-control" id="chooseFile">
								  <label class="input-group-text" for="chooseFile">Select file</label>
								</div>
                            </div>
                            <button type="submit" name="submit" class="btn btn-success">
                                Upload File
                            </button>
                        </form>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <!-- jQuery -->
    <script src="https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js"></script>
    <script>
        function readURL(input) {
            if (input.files && input.files[0]) {
                var reader = new FileReader();
                reader.onload = function (e) {
                    $('#imgPlaceholder').attr('src', e.target.result);
                }
                reader.readAsDataURL(input.files[0]); // convert to base64 string
            }
        }
        $("#chooseFile").change(function () {
            readURL(this);
        });
    </script>
</body>
</html>
file for storing the data
save.php
//save.php
<?php 
    // Database connection
    include("config.php");
     
    if(isset($_POST["submit"])) {
        // Set image placement folder
        $target_dir = "images/";
        // Get file path
        $target_file = $target_dir . basename($_FILES["fileUpload"]["name"]);
        // Get file extension
        $imageExt = strtolower(pathinfo($target_file, PATHINFO_EXTENSION));
        // Allowed file types
        $allowd_file_ext = array("jpg", "jpeg", "png");
 
        if (!file_exists($_FILES["fileUpload"]["tmp_name"])) {
           $resMessage = array(
               "status" => "alert-danger",
               "message" => "Select image to upload."
           );
        } else if (!in_array($imageExt, $allowd_file_ext)) {
            $resMessage = array(
                "status" => "alert-danger",
                "message" => "Allowed file formats .jpg, .jpeg and .png."
            );            
        } else if ($_FILES["fileUpload"]["size"] > 2097152) {
            $resMessage = array(
                "status" => "alert-danger",
                "message" => "File is too large. File size should be less than 2 megabytes."
            );
        } else if (file_exists($target_file)) {
            $resMessage = array(
                "status" => "alert-danger",
                "message" => "The File already exists."
            );
        } else {
            if (move_uploaded_file($_FILES["fileUpload"]["tmp_name"], $target_file)) {
                $sql = "INSERT INTO user (image) VALUES ('$target_file')";
                $stmt = $conn->prepare($sql);
                if($stmt->execute()){
                    $resMessage = array(
                        "status" => "alert-success",
                        "message" => "Image uploaded successfully."
                    );                 
                 }
            } else {
                $resMessage = array(
                    "status" => "alert-danger",
                    "message" => "Image can not be uploaded."
                );
            }
        }
    }
?>

Related Post