How To Insert Image In Php ?


In this tutorial, You can save your uploading images in the database table for later use. display any images, create the image gallery, etc.

In this tutorial, I show the methods for storing image from the database table.

1. Table Structure
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

Then You create a new config.php file for database configuration.

<?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 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 it to make an image source.

Here, I am storing the file name in the MySQL database.

<?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 the name or path of the image which you have stored in the database table and use it in the image source.

<?php

$sql = "select name from images where id=1";
$result = mysqli_query($con,$sql);
while($row = mysqli_fetch_array($result)){
      $image = $row['name'];
      $image_src = "upload/".$image; 
      <img src='<?php echo $image_src;  ?>' > echo '<br>';
}
?>

Demo:

Upload  Image In The Database With PHP - Php Coding Stuff

I hope it can help you...

Leave a Reply

Your privacy will not be published. Required fields are marked *

We'll share your Website Only Trusted.!!

close