How to Upload and store an image in the Database with PHP

User avatar
Mitch
Posts: 61
Joined: Mon Jan 30, 2017 4:58 am

How to Upload and store an image in the Database with PHP

Sat Apr 06, 2019 4:12 am

There are two ways of doing this –

- Save path or name of an image
- Encode image into a base64 format

1. Table structure
In the example, I am using images table for storing data.

name – This field is used to store the image file name.
image – This field is used to store the image base64 generated value.
CREATE TABLE `images` (
`id` int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT,
`name` varchar(200) NOT NULL,
`image` longtext NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
2. Configuration
Create a new config.php file.

Completed Code
<?php

$host = "localhost"; /* Host name */
$user = "root"; /* User */
$password = ""; /* Password */
$dbname = "tutorial"; /* Database name */

$con = mysqli_connect($host, $user, $password,$dbname);
// Check connection
if (!$con) {
die("Connection failed: " . mysqli_connect_error());
}
3. Save path or name
You can either save full path or name of an image in your MySQL database table. Retrieve the image name or path from the MySQL database and use to make image source.

Here, I am storing file name in MySQL database.

Completed Code
?php
include("config.php");

if(isset($_POST['but_upload'])){

$name = $_FILES['file']['name'];
$target_dir = "upload/";
$target_file = $target_dir . basename($_FILES["file"]["name"]);

// Select file type
$imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));

// Valid file extensions
$extensions_arr = array("jpg","jpeg","png","gif");

// Check extension
if( in_array($imageFileType,$extensions_arr) ){

// Insert record
$query = "insert into images(name) values('".$name."')";
mysqli_query($con,$query);

// Upload file
move_uploaded_file($_FILES['file']['tmp_name'],$target_dir.$name);

}

}
?>

<form method="post" action="" enctype='multipart/form-data'>
<input type='file' name='file' />
<input type='submit' value='Save name' name='but_upload'>
</form>
Retrieve
Select name or path of the image which you have stored in the database table and use it in image source.

Example
<?php

$sql = "select name from images where id=1";
$result = mysqli_query($con,$sql);
$row = mysqli_fetch_array($result);

$image = $row['name'];
$image_src = "upload/".$image;

?>
<img src='<?php echo $image_src; ?>' >
4. base64_encode()
You can store the full image in the Database table by converting it into the base64 format. You don’t need to store image reference in Database table e.g. name, path and not require to store the image on your server.

In PHP base64_encode() method is been used for base64 conversion. Before storing it in the database I append data:image/'.$imageFileType.';base64, text with base64 value.

Now when need to display the image just fetch the value and use it as an image source.
Note – In the example, I upload the image to directory. You can remove the upload code if you only want the image will accessible through base64 stored values in the database.
Completed Code
<?php
include("config.php");

if(isset($_POST['but_upload'])){

$name = $_FILES['file']['name'];
$target_dir = "upload/";
$target_file = $target_dir . basename($_FILES["file"]["name"]);

// Select file type
$imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));

// Valid file extensions
$extensions_arr = array("jpg","jpeg","png","gif");

// Check extension
if( in_array($imageFileType,$extensions_arr) ){

// Convert to base64
$image_base64 = base64_encode(file_get_contents($_FILES['file']['tmp_name']) );
$image = 'data:image/'.$imageFileType.';base64,'.$image_base64;
// Insert record
$query = "insert into images(image) values('".$image."')";
mysqli_query($con,$query);

// Upload file
move_uploaded_file($_FILES['file']['tmp_name'],$target_dir.$name);
}

}
?>

<form method="post" action="" enctype='multipart/form-data'>
<input type='file' name='file' />
<input type='submit' value='Save name' name='but_upload'>
</form>
Retrieve
Select the stored base64 value and using it in image source.

Example
<?php

$sql = "select image from images where id=1";
$result = mysqli_query($con,$sql);
$row = mysqli_fetch_array($result);

$image_src2 = $row['image'];

?>
<img src='<?php echo $image_src; ?>' >


Return to “WEB DESIGN, PHP, HTML”

Links

In total there are 4 users online :: 0 registered, 0 hidden and 4 guests
Registered users: No registered users
Most users ever online was 162 on Fri Dec 06, 2019 8:39 pm
Total posts 537
Total topics 415
Total members 73
Our newest member Kelly
No birthdays today