Insert Image in database using PHP and mysql makcode.in

Uploads your images in the database table for any use e.g. display user profile or product image, create the image gallery etc.

TABLE STRUCTURE

In these example, I am using image table for storing data.

CREATE TABLE `images` (
  `id` int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT,
  `name` varchar(200) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

config.php

<?php

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

$con = mysqli_connect($host, $user, $password,$dbname);
// Check connection
if (!$con) {
  die("Connection failed: " . mysqli_connect_error());
}

You can save the 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 an image source

Here I am storing the file name in the MySQL database

Insert.php

<?php
include("config.php");

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

  // Select file type
  $imageFileType = (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);
     if ($query) {
         echo "Image Inserted Successfully";
     } else
     echo "Upload Fail";
  
     // 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='upload'>
</form>

Retrive.php

  • For displaying inserted images records
<?php 

include "config.php";


$sql = "select * from images order by id desc";
$result = mysqli_query($con,$sql);
$row = mysqli_fetch_array($result);

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

?>
<img src='<?php echo $image_src;?>' width='300px' height='300px' >

Free Web Tools

Leave a Reply

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