How To Upload And Insert Image Into Mysql Database Using Php And Html

Maurice Muteti
2 min readApr 4, 2019

--

This code uploads image to a folder and saves its name in the database. All the source code required is provided below. You need to have xampp server and any code editor. In this tutorial we used sublime text.

First you need to create database.

CREATE DATABASE uploadfile;

DATABASE STRUCTURE

Then create table.

CREATE TABLE IF NOT EXISTS `uploadedimage` (
`Id` int(11) NOT NULL AUTO_INCREMENT,
`imagename` varchar(100) NOT NULL,
PRIMARY KEY (`Id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

uploadimage.php

<?php
//This code shows how to Upload And Insert Image Into Mysql Database Using Php Html.
//connecting to uploadFile database.
$conn = mysqli_connect(“localhost”, “root”, “”, “uploadFile”);
if($conn) {
//if connection has been established display connected.
echo “connected”;
}
//if button with the name uploadfilesub has been clicked
if(isset($_POST[‘uploadfilesub’])) {
//declaring variables
$filename = $_FILES[‘uploadfile’][‘name’];
$filetmpname = $_FILES[‘uploadfile’][‘tmp_name’];
//folder where images will be uploaded
$folder = ‘imagesuploadedf/’;
//function for saving the uploaded images in a specific folder
move_uploaded_file($filetmpname, $folder.$filename);
//inserting image details (ie image name) in the database
$sql = “INSERT INTO `uploadedimage` (`imagename`) VALUES (‘$filename’)”;
$qry = mysqli_query($conn, $sql);
if( $qry) {
echo “</br>image uploaded”;
}
}

?>

<!DOCTYPE html>
<html>
<body>
<! — Make sure to put “enctype=”multipart/form-data” inside form tag when uploading files →
<form action=”” method=”post” enctype=”multipart/form-data” >
<! — input tag for file types should have a “type” attribute with value “file” →
<input type=”file” name=”uploadfile” />
<input type=”submit” name=”uploadfilesub” value=”upload” />
</form>
</body>
</html>

Accessing the script using internet explorer browser

Make sure the server is started.

The image name is inserted into the database.
Imaged files are stored inside a folder.

References :

  1. http://mauricemutetingundi.blogspot.com/2017/06/upload-and-insert-image-into-database.html
  2. https://www.instructables.com/id/How-to-Upload-and-Insert-Image-Into-Mysql-Database/

--

--

Responses (2)