Upload image and preview in php

Uploading the image/videos into the database and displaying it using PHP is the way of uploading the image into the database and fetching it from the database. Using the PHP code, the user uploads the image or videos they are safely getting entry into the database and the images should be saved into a particular location by fetching these images from the database.

index.php
<head>
<title>Bootstrap Example</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.4/jquery.min.js"></script>
</head>
<br/>
<div style="padding:30px">
<form method="post" action="upload.php" enctype="multipart/form-data">
<label>Upload Image</label><br/>
<input type="file" name="image" onchange="previewImage(event);" /><br/>
<button type="submit" name="submit">Submit</button>
</form>
<div>
<img id="preview-selected-image" />
</div>
</div>
<style>
.image-preview-container {
width: 300px;
margin: 0 auto;
border: 1px solid rgba(0, 0, 0, 0.1);
padding: 3rem;
border-radius: 20px;
}
.image-preview-container img {
width: 300px;
height:100px;
display: none;
margin-bottom: 30px;
}
.image-preview-container input {
display: none;
}
</style>
<!-- code for display image before uploading -->
<script>
const previewImage = (event) => {
const imageFiles = event.target.files;
const imageFilesLength = imageFiles.length;
if (imageFilesLength > 0) {
const imageSrc = URL.createObjectURL(imageFiles[0]);
const imagePreviewElement = document.querySelector("#preview-selected-image");
imagePreviewElement.src = imageSrc;
imagePreviewElement.style.display = "block";
imagePreviewElement.style.width = "300px";
imagePreviewElement.style.height = "100px";
imagePreviewElement.style.border = "1px solid #ccc";
}
};
</script>
upload.php
<?php
// If upload button is clicked ...
if (isset($_POST['submit'])) {
$filename = $_FILES["image"]["name"];
$tempname = $_FILES["image"]["tmp_name"];
$folder = "./image/" . $filename;
include 'dbcon.php';
// Get all the submitted data from the form
$sql = "INSERT INTO image (name) VALUES ('$filename')";
// Execute query
mysqli_query($conn, $sql);
// Now let's move the uploaded image into the folder: image
if (move_uploaded_file($tempname, $folder)) {
echo "<h3> Image uploaded successfully!</h3>";
} else {
echo "<h3> Failed to upload image!</h3>";
}
}
?>
dbcon.php
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "php_tutorial";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
?>

Leave a Reply