How to CRUD operation with Image Using html jquery PHP and MySQLi
This is a basic implementation of CRUD operations with images using HTML, jQuery, PHP, and MySQLi. Make sure to adjust the code according to your specific requirements and security considerations, such as input validation and preventing SQL injection. Additionally, consider error handling and user feedback to enhance the user experience.
To implement Create, Read, Update, and Delete (CRUD) operations with images using HTML, jQuery, PHP, and MySQLi, you can follow the steps below:
- Database Setup: First, create a MySQL database table to store the image data.
sqlCREATE TABLE images (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100),
image_path VARCHAR(255)
);
- HTML Form: Create an HTML form to upload images.
html<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Image CRUD</title>
</head>
<body>
<form id="imageForm" enctype="multipart/form-data">
<input type="file" name="image" id="image">
<button type="submit">Upload</button>
</form>
<div id="imageContainer"></div>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="script.js"></script>
</body>
</html>
- jQuery for Image Upload: Write JavaScript (jQuery) to handle image upload and display.
javascript$(document).ready(function(){
$('#imageForm').submit(function(e){
e.preventDefault();
var formData = new FormData(this);
$.ajax({
url: 'upload.php',
type: 'POST',
data: formData,
success: function(response){
$('#imageContainer').html(response);
},
cache: false,
contentType: false,
processData: false
});
});
});
- PHP Script for Image Upload: Create a PHP script to handle image upload and store it in the database.
php<?php
// Database connection
$mysqli = new mysqli('localhost', 'username', 'password', 'database');
if ($_FILES['image']['name']) {
$image_name = $_FILES['image']['name'];
$image_temp = $_FILES['image']['tmp_name'];
$image_type = $_FILES['image']['type'];
if (move_uploaded_file($image_temp, 'uploads/' . $image_name)) {
$query = "INSERT INTO images (name, image_path) VALUES ('$image_name', 'uploads/$image_name')";
$mysqli->query($query);
echo "<img src='uploads/$image_name'>";
} else {
echo "Failed to upload image.";
}
}
?>
- Read Operation: Fetch and display images from the database.
php<?php
$query = "SELECT * FROM images";
$result = $mysqli->query($query);
while ($row = $result->fetch_assoc()) {
echo "<img src='" . $row['image_path'] . "'><br>";
}
?>
- Update and Delete Operations: For update and delete operations, you'll need additional HTML and PHP logic to handle editing and removing images from the database.