Skip to content Skip to sidebar Skip to footer

Upload an Image to Database and Retrieve It

Server-side file upload can exist hands implemented using PHP. There are various ways available to upload image to server and display images on the webpage. Mostly, in a dynamic web application, the uploaded image is stored in a directory of the server and the file proper name is inserted in the database. After, the images are retrieved from the server based on the file name stored in the database and display on the web page.

The image can be uploaded directly to the database without storing on the server. But it will increase the database size and web page load fourth dimension. And then, information technology's always a skillful idea to upload images to the server and store file names in the database. In this tutorial, nosotros volition show you the unabridged process to upload and store the epitome file in MySQL database using PHP.

The example lawmaking demonstrates the process to implement the file upload functionality in the web application and the following functionality will exist implemented.

  • HTML form to upload image.
  • Upload prototype to server using PHP.
  • Store file proper noun in the database using PHP and MySQL.
  • Think images from the database and brandish in the web page.

Create Datbase Table

To shop the image file proper noun a table need to be created in the database. The following SQL creates an images tabular array with some basic fields in the MySQL database.

          CREATE          TABLE          `images` (          `id`          int(xi)          NOT Zip          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          Non NULL          DEFAULT          '1',          PRIMARY Primal          (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;        

Database Configuration (dbConfig.php)

The dbConfig.php file is used to connect and select the MySQL database. Specify the database hostname ($dbHost), username ($dbUsername), countersign ($dbPassword), and proper noun ($dbName) as per your MySQL credentials.

          <?php
// Database configuration
$dbHost = "localhost" ;
$dbUsername = "root" ;
$dbPassword = "root" ;
$dbName = "codexworld" ; // Create database connection
$db = new mysqli ( $dbHost , $dbUsername , $dbPassword , $dbName ); // Bank check connection
if ( $db -> connect_error ) {
    die(
"Connexion failed: " . $db -> connect_error );
}
?>

Upload Form HTML

Create an HTML form to permit the user to choose a file they want to upload. Brand certain <form> tag contains the post-obit attributes.

  • method="mail"
  • enctype="multipart/form-information"

Also, make sure <input> tag contains type="file" aspect.

<course          action="upload.php"          method="post"          enctype="multipart/form-data">     Select Paradigm File to Upload:     <input          type="file"          name="file">     <input          type="submit"          proper noun="submit"          value="Upload"> </grade>        

php-upload-image-file-to-server-codexworld

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.
  • Go the file extension using pathinfo() part in PHP and validate the file format to check whether the user selects an epitome file.
  • Upload image to server using move_uploaded_file() function in PHP.
  • Insert image file name in the MySQL database using PHP.
  • Upload condition will exist shown to the user.
          <?php
// Include the database configuration file
include 'dbConfig.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" ][ "proper noun" ])){
// Permit 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 fault uploading your file." ;
        }
    }else{
$statusMsg = 'Sorry, just JPG, JPEG, PNG, GIF, & PDF files are allowed to upload.' ;
    }
}else{
$statusMsg = 'Delight select a file to upload.' ;
}
// Display condition bulletin
echo $statusMsg ;
?>

Display Images from Database

Now we will think the uploaded images from the server based on the file names in the database and display images in the spider web page.

  • Include the database configuration file.
  • Fetch images from MySQL database using PHP.
  • List images from the uploads directory of the server.
          <?php
// Include the database configuration file
include 'dbConfig.php' ; // Get images from the database
$query = $db -> query ( "SELECT * FROM images Gild 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 } ?>

upload-image-retrieve-from-database-php-mysql-codexworld

Create Dynamic Paradigm Gallery with jQuery, PHP & MySQL

Decision

Here nosotros have shown the almost effective fashion to implement image upload functionality on the website. Yous can easily extend the file upload functionality as per your requirements. For providing the ameliorate user-interface you tin can integrate the Ajax File Upload functionality.

Upload multiple images using jQuery, Ajax and PHP

Are you desire to get implementation assistance, or modify or heighten the functionality of this script? Submit Paid Service Request

If you have any questions about this script, submit it to our QA customs - Inquire Question

fordesmagal.blogspot.com

Source: https://www.codexworld.com/upload-store-image-file-in-database-using-php-mysql/#:~:text=Get%20the%20file%20extension%20using,be%20shown%20to%20the%20user.

Post a Comment for "Upload an Image to Database and Retrieve It"