Get all image files name inside directory and store in database.

Step 1:   Create connection for  database  now we uses  mysql.

/* Establish  database connection*/
define('DB_NAME', 'YOUR_DB_NAME');
define('DB_HOST', 'localhost');
define('DB_USERNAME', 'YOUR_DB_USER_NAME');
define('DB_PASSWORD', 'YOUR_DB_PASSWORD');
$link = mysqli_connect(DB_HOST, DB_USERNAME, DB_PASSWORD, DB_NAME);
if (!$link) {
    die('could not connect: ' . mysql_error());
}
/* Establish  database connection*/

Step 2: Create table images which save  image name
/*Create table images  which store image names*/
CREATE TABLE `images` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `image` varchar(250) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=86 DEFAULT CHARSET=latin1;

/*Create table which store image names*/


Step 3:  create function to get images name form directory  and store in images table

/* Function getImageName  that will return all images name within directory and also save image name in images table */
function getImageName($dirimg = NULL) {
    $images = array();
    foreach (glob($dirimg . '/*.*') as $file) {
        $filename = explode("/", $file);
         $images[] = $filename[1];
         $result = mysqli_query($link, "INSERT INTO images (image) VALUES('" . $filename[1] . "')");
          if (!$result) {
          die('Invalid query: ' . mysql_error());
          }
    }

    return $images;
}
/* Function getImageName  that will return all images name within directory  and also save image name in images table */


Step 4: call getImageName   function  to get image name in a array  and in this function we pass  directory name 'gimages' .
$allDirIamges = getImageName('gimages');

NOTE:  in this case gimages  directory  and  getimagename.php  in same directory.
Find below full integrated code getimagename.php with all steps.
For any query email any time at  pankajtec@gmail.com .

file getimagename.php

<?php

/**
 * @package get all file names  with directory
 * @author Pankaj Singh
 * @copyright (c) 2017 Panky
 *
 */
define('DB_NAME', 'YOUR_DB_NAME');
define('DB_HOST', 'localhost');
define('DB_USERNAME', 'YOUR_DB_USER_NAME');
define('DB_PASSWORD', 'YOUR_DB_PASSWORD');
$link = mysqli_connect(DB_HOST, DB_USERNAME, DB_PASSWORD, DB_NAME);
if (!$link) {
    die('could not connect: ' . mysql_error());
}



$allDirIamges = getImageName('gimages');


/**
 * @param string $dirimg
 * @author Pankaj Singh
 * @return images name $images as array
 *
 */
function getImageName($dirimg = NULL) {
    $images = array();
    foreach (glob($dirimg . '/*.*') as $file) {
        $filename = explode("/", $file);
         $images[] = $filename[1];
         $result = mysqli_query($link, "INSERT INTO images (image) VALUES('" . $filename[1] . "')");
          if (!$result) {
          die('Invalid query: ' . mysql_error());
          }
    }

    return $images;
}
?>

Comments

Popular Posts