How to File Upload in PHP With jQuery AJAX mysqli
To create a file upload functionality in PHP with jQuery AJAX and perform CRUD operations using MySQLi, you'll need to follow these steps:
- Create Database Table: Set up a MySQL database table to store file information.
- Create HTML Form: Design an HTML form for file upload and other CRUD operations.
- PHP File Handling: Write PHP scripts to handle file upload, CRUD operations, and AJAX requests.
- jQuery AJAX: Implement jQuery AJAX to communicate between the HTML form and PHP scripts.
Here's a basic example to guide you through the process:
1. Create Database Table
sqlCREATE TABLE files (
id INT AUTO_INCREMENT PRIMARY KEY,
filename VARCHAR(255),
file_path VARCHAR(255),
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
2. HTML Form
html<form id="fileUploadForm" enctype="multipart/form-data">
<input type="file" name="file" id="file">
<button type="submit" id="uploadBtn">Upload File</button>
</form>
<div id="fileList"></div>
3. PHP File Handling (upload.php)
php<?php
// Connection to MySQL
$mysqli = new mysqli("localhost", "username", "password", "database");
// File upload directory
$targetDir = "uploads/";
if(isset($_FILES["file"]["name"])){
$fileName = basename($_FILES["file"]["name"]);
$targetFilePath = $targetDir . $fileName;
$fileType = pathinfo($targetFilePath, PATHINFO_EXTENSION);
// Upload file to server
if(move_uploaded_file($_FILES["file"]["tmp_name"], $targetFilePath)){
// Insert file details into database
$insert = $mysqli->query("INSERT into files (filename, file_path) VALUES ('$fileName', '$targetFilePath')");
if($insert){
echo "File uploaded successfully.";
} else {
echo "File upload failed, please try again.";
}
} else {
echo "Sorry, there was an error uploading your file.";
}
}
?>
4. jQuery AJAX
javascript$(document).ready(function(){
// File upload via AJAX
$("#fileUploadForm").submit(function(e){
e.preventDefault();
$.ajax({
url: 'upload.php',
type: 'POST',
data: new FormData(this),
contentType: false,
cache: false,
processData:false,
success: function(response){
alert(response);
// You can handle response as needed (e.g., display success message, update file list, etc.)
}
});
});
// Load file list via AJAX
function loadFiles(){
$.ajax({
url: 'get_files.php',
type: 'GET',
success: function(response){
$("#fileList").html(response);
}
});
}
loadFiles(); // Load files on page load
// Perform CRUD operations via AJAX as needed
});
In the above code:
- Replace
"username","password", and"database"with your MySQL credentials. - Ensure the
uploadsdirectory exists and is writable. - Implement additional PHP scripts (
get_files.php) to retrieve file list and handle other CRUD operations.
This is a basic example to get you started. Ensure to enhance security measures and error handling in a production environment.