Upload File or Image With Size Limit to MySQL Database Using PHP.
First, this is an example code for uploading files to the database, so take it as inspiration and set the structure of the table and variable names according to your needs.
Follow the given steps.
- This is the database and table structure we are creating.
-- Creating Database
CREATE DATABASE `crud_operation_db`;
-- Creating Table
CREATE TABLE `crud_operation_db`.`crud_upload_file` (
`Auto ID` INT NOT NULL AUTO_INCREMENT,
`Name` VARCHAR(255) NOT NULL,
`File or Image` VARCHAR(255) NOT NULL,
`Create at` DATE NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`Auto ID`)
) ENGINE = InnoDB;
- This is the connection to the database we are making in PHP. (config.php)
<?php
// Creating Variables
$server_name = "localhost";
$user_name = "root";
$password = "";
$db_name = "crud_operation_db";
// Creating Connection
$conn = new mysqli($server_name, $user_name, $password, $db_name);
// Checking Connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
?>
- Create a folder in the root folder where we will save the uploaded files.
- Complete the following list on your HTML form like in the given source code.
- Set upload PHP file to your action attribute.
- Set method to POST.
- Add enctype="multipart/form-data".
- Set the name of the input file as you would write in the PHP file.
<form action="upload_file.php" method="POST" enctype="multipart/form-data">
<input type="text" name="crud_name" placeholder="Enter Your Name">
<input type="file" name="crud_file">
<input type="submit" value="Upload" name="upload_button">
</form>
- Now, this is a specific PHP script to save the file to the database. Here we are sending the file name to the database, and using the move_uploaded_file() function we are saving it to a folder on our server.
<?php
// Getting config file
require_once 'config.php';
if (isset($_POST['upload_button'])) {
// Getting user name
$crud_name = $_POST['crud_name'];
// Getting file name
$file_name = basename($_FILES['crud_file']['name']);
// Getting file size
$file_size = $_FILES['crud_file']['size'];
// Adding size in bytes
$sizeinbytes = 2000000;
// Folder setup
$folder = 'uploads/' . $file_name;
// Checking File Size
if ($file_size > $sizeinbytes) {
echo "File size must be less than 2MB.";
} else {
// Moving file in folder (tmp_name is required)
if (move_uploaded_file($_FILES["crud_file"]["tmp_name"], $folder)) {
// Sending file name to database
$sql = "INSERT INTO `crud_upload_file` (`Auto ID`, `Name`, `File or Image`, `Create at`) VALUES (NULL, '$crud_name', '$file_name', current_timestamp());";
mysqli_query($conn, $sql);
echo 'Successfully! Submitted <a href="file_input.php">Go Back</a>.';
}
}
}
?>
- All set:)
0 Comments