How to upload an image to a database using PHP PDO - onlyxcodes

Saturday, 6 July 2024

How to upload an image to a database using PHP PDO

Hi there, friends I'll share a short tutorial on how to use PHP PDO to upload an image to a database, which may be helpful for your project or web application. Additionally, a MySQL image upload will take place. We now have CRUD Tutorials, but I didn't cover this in them. This article covers correct image validation, i.e., uploading only valid image extensions and taking into account image size. Now let's explore the PHP image upload.


how to upload an image to a database using php pdo

Table Content

1. Create a Database and Table

2. dbconfig.php

3. index.php

4. PHP Image Upload Code with PDO


1. Create a Database and Table

The database "file_upload_db" is used in this tutorial; therefore, make one and enter the following SQL code into your PhpMyAdmin to create the "tbl_user" user table.


CREATE TABLE `tbl_user` (
  `id` int(11) NOT NULL,
  `username` varchar(100) NOT NULL,
  `userpicture` varchar(255) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;

2. dbconfig.Php

With PDO Query/Extension, a basic host/database setup file has been built. Modify the credentials to match your setup.


<?php

$db_host="localhost"; 
$db_user="root";	
$db_password="";	
$db_name="file_upload_db";	

try
{
	$db=new PDO("mysql:host={$db_host};dbname={$db_name}",$db_user,$db_password);
	$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOEXCEPTION $e)
{
	$e->getMessage();
}

?>

3. index.php

This is a simple HTML form made with Bootstrap. You can add more fields. I've included the username and user image fields for the user.


<form method="post" class="form-horizontal" enctype="multipart/form-data">
					
	<div class="form-group">
	<label class="col-sm-3 control-label">Username</label>
	<div class="col-sm-6">
	<input type="text" name="txt_username" class="form-control" />
	</div>
	</div>
				
				
	<div class="form-group">
	<label class="col-sm-3 control-label">Select File</label>
	<div class="col-sm-6">
	<input type="file" name="txt_file" class="form-control" />
	</div>
	</div>
				
	<div class="form-group">
	<div class="col-sm-offset-3 col-sm-6 m-t-15">
	<button type="submit" name="btn_upload" class="btn btn-success btn-lg btn-block" >Upload</button>
	</div>
	</div>
				
</form>

<?php
			
if(isset($errMSG))
{
?>
	<div class="alert alert-danger alert-dismissible">
		<strong>WRONG ! <?php echo $errMSG; ?></strong>
		<button type="button" class="close" data-dismiss="alert">&times;</button>
	</div>
<?php
}
else if(isset($successMSG))
{
?>
	<div class="alert alert-success alert-dismissible">
		<strong>SUCCESS ! <?php echo $successMSG; ?></strong>
		<button type="button" class="close" data-dismiss="alert">&times;</button>
	</div>
<?php
}
?>

The Form Above Will Appear Like This:


image upload form

Since I used her bootstrap for this tutorial, as I previously mentioned, the real file code is large. For this reason, I have just included the most crucial and essential code here; the designing code has been left out. Let's move on to the following point quickly.


4. PHP Image Upload Code with PDO

Place the PHP code that follows directly above the tag. This script inserts the user name and an image, does suitable image validation, and uses bootstrap design to display an appropriate message in the event of a problem.


<?php
 
 require_once 'dbconfig.php';
 
 if(isset($_POST['btn_upload']))
 {
  $username = $_POST['txt_username'];// user name
  
  $imgFile = $_FILES['txt_file']['name'];
  $tmp_dir = $_FILES['txt_file']['tmp_name'];
  $imgSize = $_FILES['txt_file']['size'];
  
  
  if(empty($username)){
   $errMSG = "Please Enter Username.";
  }
  else if(empty($imgFile)){
   $errMSG = "Please Select Image File.";
  }
  else
  {
   $upload_dir = 'upload/'; // upload directory
 
   $imgExt = strtolower(pathinfo($imgFile,PATHINFO_EXTENSION)); // get image extension
  
   // valid image extensions
   $valid_extensions = array('jpeg', 'jpg', 'png', 'gif'); // valid extensions
  
   // rename uploading image
   $userpic = rand(1000,1000000).".".$imgExt;
    
   // allow valid image file formats
   if(in_array($imgExt, $valid_extensions)){   
    // Check file size '5MB'
    if($imgSize < 5000000) {
     move_uploaded_file($tmp_dir,$upload_dir.$userpic);
    }
    else{
     $errMSG = "Sorry, your file is too large.";
    }
   }
   else{
    $errMSG = "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";  
   }
  }
  
  
  // if no error occured, continue ....
  if(!isset($errMSG))
  {
   $stmt = $db->prepare('INSERT INTO tbl_user(username,userpicture) VALUES(:uname,:upic)');
   $stmt->bindParam(':uname',$username);
   $stmt->bindParam(':upic',$userpic);
   
   if($stmt->execute())
   {
    $successMSG = "new record succesfully inserted ...";
    //header("refresh:3;index.php"); // redirects image view page after 5 seconds.
   }
   else
   {
    $errMSG = "error while inserting....";
   }
  }
 }
?>

Download Codes

No comments:

Post a Comment

Post Bottom Ad