File/Image Upload in PHP MySQL Database Tutorial

Image file upload in PHP mysql; in this tutorial i am going to show you how to upload file/image into mysql database using php.

In this how to insert image in mysql database using php source code example; i will create a image table in database and create image/file upload form. Then create file/image insert/save/store into database and directory using PHP MySQL.

And as well as, you can use free this file upload in php and mysql database script with your apps.

Image/File Upload in PHP MySQL Database

Use the below given steps to create image file upload in to mysql database using php code:

  • Step 1 – Start Apache Web Server
  • Step 2 – Create PHP Project
  • Step 3 – Create Table and Database Connection File
  • Step 4 – Create Image File Upload Html Form
  • Step 5 – Create PHP File to Insert Image File into DB
  • Step 6 – Test Insert Data PHP App

Step 1 – Start Apache Web Server

Now, you need to start your apache web server. And as well as start Apache and mysql web server. You can see in the image below how to start apache and mysql server:

start xampp apache mysql server
start xampp apache mysql server

Step 2 – Create PHP Project

In step 2, navigate to your xampp/htdocs/ directory. And inside xampp/htdocs/ directory, create one folder. And you can name this folder anything.

Here, I will “demo” the name of this folder. Then open this folder in any text editor (i will use sublime text editor).

Step 3 – Create Table and Database Connection File

In step 3,, you need to create database and table. So run the following sql query to create database and table:

CREATE DATABASE my_db;


CREATE TABLE `images` (
`custId` INT(11) NOT NULL AUTO_INCREMENT,
`file` VARCHAR(255) NULL DEFAULT NULL,
`type` VARCHAR(255) NULL DEFAULT NULL,
`size` VARCHAR(255) NULL DEFAULT NULL,
PRIMARY KEY (`id`)
)
COLLATE='latin1_swedish_ci'
ENGINE=InnoDB
AUTO_INCREMENT=1;


Then create a php file that named mydb.php. Which is used to connect phpmyadmin mysql database to project folder(demo).

So, now create mydb.php file and add the below given code into your file:

<?php

    $hName='localhost'; // host name

    $uName='root';   // database user name

    $password='';   // database password

    $dbName = "my_db"; // database name

    $dbCon = mysqli_connect($hName,$uName,$password,"$dbName");

      if(!$dbCon){
          die('Could not Connect MySql Server:' .mysql_error());
      }
?>

Step 4 – Create Image File Upload Html Form

In step 4, create a php file that named index.php. Which is used to display form image upload form. Using this form, you can insert image file database in php:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>how to upload file in mysql database using php - Laratutorials.com</title>
</head>
<body>
	<form action="insert.php" method="post" enctype="multipart/form-data">
	    <h2>PHP Upload File</h2>
	    <label for="file_name">Filename:</label>
	    <input type="file" name="anyfile" id="anyfile">
	    <input type="submit" name="submit" value="Upload">
	    <p><strong>Note:</strong> Only .jpg, .jpeg, .gif, .png formats allowed to a max size of 5 MB.</p>
	</form>
</body>
</html>

Step 5 – Create PHP File to Insert Image File into DB

In step 5, create one file that named insert.php file. This php file code will insert/store image file data into mysql database and directory.

Note that, If the image file upload is successfully inserted / stored into database, it will display success message. Otherwise if there is any error, it will display error message.

So, add the below code into your insert.php file:

<?php
include_once 'mydb.php';
// Check if the form was submitted
if($_SERVER["REQUEST_METHOD"] == "POST"){
    // Check if file was uploaded without errors
    if(isset($_FILES["anyfile"]) && $_FILES["anyfile"]["error"] == 0){
        $allowed = array("jpg" => "image/jpg", "jpeg" => "image/jpeg", "gif" => "image/gif", "png" => "image/png");
        $filename = $_FILES["anyfile"]["name"];
        $filetype = $_FILES["anyfile"]["type"];
        $filesize = $_FILES["anyfile"]["size"];
    
        // Validate file extension
        $ext = pathinfo($filename, PATHINFO_EXTENSION);
        if(!array_key_exists($ext, $allowed)) die("Error: Please select a valid file format.");
    
        // Validate file size - 10MB maximum
        $maxsize = 10 * 1024 * 1024;
        if($filesize > $maxsize) die("Error: File size is larger than the allowed limit.");
    
        // Validate type of the file
        if(in_array($filetype, $allowed)){
            // Check whether file exists before uploading it
            if(file_exists("upload/" . $filename)){
                echo $filename . " is already exists.";
            } else{
                if(move_uploaded_file($_FILES["anyfile"]["tmp_name"], "upload/" . $filename)){

                    $sql="INSERT INTO images(file,type,size) VALUES('$filename','$filetype','$filesize')";
                    
                    mysqli_query($conn,$sql);

                    echo "Your file was uploaded successfully.";
                }else{

                   echo "File is not uploaded";
                }
                
            } 
        } else{
            echo "Error: There was a problem uploading your file. Please try again."; 
        }
    } else{
        echo "Error: " . $_FILES["anyfile"]["error"];
    }
}
?>

Step 6 – Test Insert Data PHP App

Finally, you need to open your browser and type http://localhost/demo/ this run project on local machine.

Recommended PHP Tutorials

Be First to Comment

Leave a Reply

Your email address will not be published. Required fields are marked *