Instructions to Upload and Store Image File in Database utilizing PHP and MySQL

Share on FacebookTweet about this on TwitterShare on Google+Share on LinkedInPin on PinterestPrint this pageEmail this to someone

Server-side record transfer can be effectively executed utilizing PHP. There are different routes accessible to transfer picture to server and show pictures on the website page. By and large, in a dynamic web application, the transferred picture is put away in an index of the server and the document name is embedded in the database. Afterward, the pictures are recovered from the server in view of the document name put away in the database and show in the site page.

The picture can be transferred straightforwardly to the database without putting away on the server. In any case, it will build the database size and site page stack time. In this way, its dependably a smart thought to transfer picture to the server and store document name in the database. In this instructional exercise, we will demonstrate to you the whole procedure to transfer and store the picture record in MySQL database using PHP.
The example code demonstrates the process to implement the file upload functionality in the web application and the following functionality will be implemented.

  • HTML form to upload image.
  • Upload image to server using PHP.
  • Store file name in the database using PHP and MySQL.
  • Retrieve images from the database and display in the web page.

Create Datbase Table In MySql
To store the image file name a table need to be created in the database. The following SQL creates an images table with some basic fields in the MySQL database.

1
2
3
4
5
6
7
CREATE TABLE `images` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`file_name` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`uploaded_on` datetime NOT NULL,
`status` enum('1','0') COLLATE utf8_unicode_ci NOT NULL DEFAULT '1',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

Database Configuration (Config.php)
The Config.php file is used to connect and select the MySQL database. Specify the database hostname ($Host), username ($Username), password ($Password), and name ($Name) as per your MySQL credentials.

READ  How To Work With Codeigniter Database Caching
1
2
3
4
5
6
7
8
9
10
11
12
13
<?php // Database configuration
$Host = "localhost";
$Username = "root";
$Password = "root";
$Name = "Queryanswer";
// Create database connection
$db = new mysqli($dbHost, $dbUsername, $dbPassword, $dbName);

// Check connection
if ($db->connect_error) {
    die("Connection failed: " . $db->connect_error);
}
?>

Upload Form HTML
Create an HTML form to allow the user to choose a file they want to upload. Make sure

tag contains the following attributes.

1
2
3
method="post"
enctype="multipart/form-data"
Also, make sure <input type="text" /> tag contains type="file" attribute.
1
2
3
4
5
<form action="upload.php" method="post" enctype="multipart/form-data">
    Select Image File to Upload:
    <input type="file" name="file">
    <input type="submit" name="submit" value="Upload">
</form>

The file upload form will be submitted to the upload.php file to upload image to the server.

Upload File to Server and Store in Database (upload.php)
The upload.php file handles the image upload functionality and shows the status message to the user.

  • Include the database configuration file to connect and select the MySQL database.
  • Get the file extension using pathinfo() function in PHP and validate the file format to check whether the user selects an image file.
  • Upload image to server using move_uploaded_file() function in PHP.
  • Insert image file name in the MySQL database using PHP.
  • Upload status will be shown to the user.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
<?php
// Include the database configuration file
include 'Config.php';
$statusMsg = '';

// File upload path
$targetDir = "uploads/";
$fileName = basename($_FILES["file"]["name"]);
$targetFilePath = $targetDir . $fileName;
$fileType = pathinfo($targetFilePath,PATHINFO_EXTENSION);

if(isset($_POST["submit"]) && !empty($_FILES["file"]["name"])){
    // Allow certain file formats
    $allowTypes = array('jpg','png','jpeg','gif','pdf');
    if(in_array($fileType, $allowTypes)){
        // Upload file to server
        if(move_uploaded_file($_FILES["file"]["tmp_name"], $targetFilePath)){
            // Insert image file name into database
            $insert = $db->query("INSERT into images (file_name, uploaded_on) VALUES ('".$fileName."', NOW())");
            if($insert){
                $statusMsg = "The file ".$fileName. " has been uploaded successfully.";
            }else{
                $statusMsg = "File upload failed, please try again.";
            }
        }else{
            $statusMsg = "Sorry, there was an error uploading your file.";
        }
    }else{
        $statusMsg = 'Sorry, only JPG, JPEG, PNG, GIF, & PDF files are allowed to upload.';
    }
}else{
    $statusMsg = 'Please select a file to upload.';
}

// Display status message
echo $statusMsg;
?>

Display Images from Database
Now we will retrieve the uploaded images from the server based on the file names in the database and display images in the web page.

  • Include the database configuration file.
  • Fetch images from MySQL database using PHP.
  • List images from the uploads directory of the server.
READ  MySQL delete duplicate records but keep latest
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<?php
// Include the database configuration file
include 'Config.php';

// Get images from the database
$query = $db->query("SELECT * FROM images ORDER BY uploaded_on DESC");

if($query->num_rows > 0){
    while($row = $query->fetch_assoc()){
        $imageURL = 'uploads/'.$row["file_name"];
?>
    <img src="<?php echo $imageURL; ?>" alt="" />
<?php }
}else{ ?>
    <p>No image(s) found...</p>
<?php } ?>

Share on FacebookTweet about this on TwitterShare on Google+Share on LinkedInPin on PinterestPrint this pageEmail this to someone

Leave a Reply

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