Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chris Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Upload multiple image to mysql

Status
Not open for further replies.

seek4need

Technical User
Aug 12, 2008
14
US
Hi,

Do you have any example.. how to upload multiple images and title to mysql database. I am looking only to store image path. Image need to store in a seperate directory.

Thanks a lot in advance...!


Thanks,
SB

 
Keith,

Are you uploading the images to directory or database?

Are you going to create the index in directory contents. How we can do that?

i want to store the image path. I don't want to store the image in BLOB.


Thanks,
SB
 
I copy the image to the directory, then create the database record if no error occurred.

What is it that you need help with? Creating the database record is no different than any other SQL query.
 
I am new to PHP, I am looking a example how to upload multiple images to mysql.

when we upload the image. The image need to copy to a directory and the directory path or reference value need to store into mysql (which we are able to retrieve the image by using directory path or reference value).


Thanks,
SB

 
why not use Gallery2 by menalto?

or you could use something like this which allows multiple uploads by way of a single zip file (from one of my earlier contributions).

Code:
<?php

define ("MAXSIZE", 400, false); //this is the max size in pixels that the images will be scaled to
define ("IMAGEPATH", "./images/", false); // the relative path (or absolute) to save albums
define ("ALLOWZIP", true); //defines whether bulk uploads are allowed in zip format.  Must support unix ZIP commands.
define ("INIT", true); // change this to false to stop the file initialisation
define ("MAXFILESIZE", ini_get("upload_max_filesize")); //maximum file upload size;
define ("LOCALTMP", "./localtmp", false); //temporary storage for uploaded zip files

switchboard(); 	//start the machine
function switchboard(){
	if (INIT) init(); //create the directories etc
	$action = isset($_POST['action']) ? $_POST['action'] : '';
	switch ($action) {

		case "uploadfile":
			processUploadedFile();
		break;
		
		case "Upload":
			displayUploadForm();
			break;
			
		break;
			displayUploadForm();
	}
}

function init(){
	$u = umask(0);

	if (!file_exists(IMAGEPATH)){
		mkdir(IMAGEPATH, 0777);
	}
	if (!file_exists(LOCALTMP)){
		mkdir (LOCALTMP, 0777);
	}
	umask ($u);
}

function getTempDir(){
	umask(0);
	$dir = "./".uniqid("tempzip_", true) .'/';
	mkdir ($dir);
	return $dir;
}


function displayUploadForm($msg=NULL){
	$maxsize = MAXFILESIZE;
	$msg = (empty($msg)) ? NULL: '<div class="errorMessage">'.$msg.'</div>';
	$shortdescription = (isset($_POST['shortdescripton'])) ? $_POST['shortdescripton'] : '';
	$contentObject = <<<HTML
$msg
<form method="post" action="{$_SERVER['PHP_SELF']}" enctype="multipart/form-data" >
<fieldset>
	<legend>Upload images</legend>
	<p>You can upload gif, png or jpegs either singly or in bulk as a zip file</p>
	Choose file (max $maxsize): <input type="file" name="upload" /><br/>
	Short description: <input type="text" maxlength="255" name="shortdescription" value="$shortdescription" /><br/>
	Which album: $select
	<input type="submit" name="submit" value="Upload" />
	<input type="hidden" name="action" value="uploadfile" />
</fieldset>
</form>
HTML;
	echo $contentObject;
}

function processUploadedFile(){
	//check for errors
	$msg = "";
	if (isset($_FILES['upload'])){
		switch ($_FILES['upload']['error']){
			case 0:
				break;
			case 1:
			case 2:
				$msg = "The uploaded file is too large"; 
				break;
			case 3:
				$msg = "The uploaded file was only partially uploaded";
				break;
			case 4:
				$msg = "No file was uploaded";
				break;
			case 6:
			case 7:
			case 8;
				$msg = "There was a problem saving ths uploaded file.";
				break;
		}
	}
	
	//if we have a problem, tell the user
	if (!empty($msg)){
		displayUploadForm($msg);
		exit();
	}
	
	//check the file type.
	//simple check against the file extension.  not ideal...
	if (!empty($_POST['upload']['type'])){
		$type = $_POST['upload']['type'];
	}else {
		$type = getFileType($_FILES['upload']['name']);
	}
	
	switch ($type){
		case "application/x-zip":
			if (ALLOWZIP){
				$tmpdir = getTempDir();
				if (!move_uploaded_file($_FILES['upload']['tmp_name'], $tmpdir."tmpzipfile.zip")){
					displayUploadForm("Problem processing zip file");
					exit();
				}
				processUploadedZipFile($tmpdir, "tmpzipfile.zip", $albumName);
				
			} else {
				displayUploadForm("Sorry we do not allow Zip files");
			}
			break;
		case "unsupported":
			displayUploadForm("Only zip files and jpegs are allowed to be uploaded");
			exit();
			break;
		default:
			$extension = getExtensionFromType($type);
			$uid = uniqid("photo_", true) .".$extension";
			$newName = IMAGEPATH.$albumName.'/'.$uid;
			if (!move_uploaded_file($_FILES['upload']['tmp_name'], $newName )){
				displayUploadForm("Problem saving this file");
				exit();
			} else {
				processUploadedPhoto($uid,  $type, $albumName);
			}		
	}
	displayUploadForm("all Done");
}

function processUploadedPhoto($file, $type){

	//where should the resultant file go
	$resizedfile = reSizePhoto(IMAGEPATH.$file, $type);
	if (!$resizedfile){
		displayUploadForm("Problem resizing the photo");
		unlink(IMAGEPATH.$file);
		exit();
	}
	
	//save the metadata for the file
	$shortdescription = addslashes (trim($_POST['shortdescription']));
	$orientation = $GLOBALS['orientation'];
	$fileName = $file;
	saveToDatabase (array($file, $shortdesription, $orientation, $type));
}

function saveToDatabase($data){
	array_walk($data, 'cleanse');
	$query = "insert into ". TABLENAME ." (imageID, imagePath, imageDescription, imageOrientation, imageType) values (null, '%s', '%s', '%s', '%s')";
	$result = mysql_query( vsprintf($query, $data));
	if (!$result){
		echo mysql_error();
		exit;
	} else {
		return true;
	}
}

function cleanse ($data){
	return mysql_real_escape_string(trim($data));
}
function processUploadedZipFile($dir, $file, $albumName){
	
	$command = "unzip $file";
	//unzip the file to the new directory
	exec (escapeshellcmd($command));

	//iterate over the directory
	$fh = opendir($dir);
	while ( false !== ($file = readdir($fh))){
		if (!is_file($file)){
			//do nothing
		}
		//really need a function to test the filetype naturally here ...
		$type = getfiletype($dir.$file);
		$extension = getExtensionFromType($type);
		if ( ($type  !== "unsupported") && ($type !== "application/x-zip") ){
			processUploadedPhoto($dir.$file, $type, $albumName);
		} else {
			//do nothing
		}
	}
	removeDirectory($dir, false);
}

function getfiletype($file){
	if (function_exists("mime_content_type")){
		return(mime_content_type($file));
	}else{
		$ext = getExtension($file);
		switch ($ext){
			case "jpeg":
			case "jpg":
				return "image/jpeg";
			break;
			case "gif":
				return "image/gif";
			break;
			case "png":
				return "image/png";
			break;
			case "zip":
				return "application/x-zip";
				break;
			default:
				return "unsupported";
		}
	}
}
function getExtension($file){
	$parts = pathinfo($file);
	return ($parts['extension']);
}
function getExtensionFromType($type){
	switch ($type){
		case "image/jpeg":
			return "jpeg";
		break;
		case  "image/gif":
			return "gif";
		break;
		case  "image/png":
			return "png";
		break;
	}
}

function reSizePhoto($file, $type){
	$newsize = MAXSIZE;
	//we know it is a jpeg because this is a limited applet
	//but allow for future expansion! 
	set_time_limit(20);
	switch ($type) {
		
		case 'image/jpeg':
			$src_img = imagecreatefromjpeg($file);
			$func = 'imagejpeg';
			$ext = '.jpeg';
			break;
		case 'image/gif':
			$src_img = imagecreatefromgif($file);
			$func = 'imagegif';
			$ext = '.gif';
			break;
		case 'image/png':
			$src_img = imagecreatefrompng($file);
			$func = 'imagepng';
			$ext = '.png';
			break;
		default:
			displayUploadForm("error - file is not of a supported image type");
			exit();
	}
	
	if ($src_img == '') {
		displayUploadForm("error - file is not a $type file");
		exit();
	}
	
	//get current image sizes
	
	$old_x=imageSX($src_img);
	$old_y=imageSY($src_img);
	
	if ($old_x > $old_y){
		$GLOBALS['orientation'] = "hr";
		if ($old_x >= $newsize){
			$thumb_w=$newsize;
			$thumb_h=$old_y*($newsize/$old_x);
		} else {
			return $file;
		}
	} elseif ($old_x < $old_y) {
		$GLOBALS['orientation'] = "vt";
		if ($old_y >= $newsize){	
			$thumb_w=$old_x*($newsize/$old_y);
			$thumb_h=$newsize;
		} else {
			return $file;
		}
	} else {
		$GLOBALS['orientation'] = "hr";
		if ($old_y >= $newsize){
			$thumb_w= $thumb_h = $newsize; 
		} else {
			return $file;
		}
	}
	
	$dst_img=ImageCreateTrueColor($thumb_w,$thumb_h);
	imagecopyresampled($dst_img,$src_img,0,0,0,0,$thumb_w,$thumb_h,$old_x,$old_y); 
	
	$func($dst_img,$file); 
	imagedestroy($dst_img);
	imagedestroy($src_img);	
	return $file;
}

function removeDirectory($dirname,$only_empty=false) {
	//taken from php.net user notes on rmdir()
    if (!is_dir($dirname))
        return false;
    $dscan = array(realpath($dirname));
    $darr = array();
    while (!empty($dscan)) {
        $dcur = array_pop($dscan);
        $darr[] = $dcur;
        if ($d=opendir($dcur)) {
            while ($f=readdir($d)) {
                if ($f=='.' || $f=='..')
                    continue;
                $f=$dcur.'/'.$f;
                if (is_dir($f))
                    $dscan[] = $f;
                else
                    unlink($f);
            }
            closedir($d);
        }
    }
    $i_until = ($only_empty)? 1 : 0;
    for ($i=count($darr)-1; $i>=$i_until; $i--) {
        @rmdir($darr[$i]);
	}
    return (($only_empty)? (count(scandir)<=2) : (!is_dir($dirname)));
}
?>

if you want to upload multiple individual files then you will need to adjust the form and the process function to look for arrays. not difficult, but i think that the zip function is neater. downside is that each zip file can only have one 'description'.

 
The final solution would depend on your application.

The ones I use are for picture gallery websites. The pictures are supplied from a number of sources and vary in size considerably. I manually resize them to a standard size then FTP them to a specific directory on the server. The admin section of the website automatically checks the 'image' directory, adds new pictures to the database and removes any which have been deleted. Only the path and picture name are added to the database at this stage. The admin section then dislays a list of incomplete files and the people at the gallery complete the picture details - name, medium, artist, style, size and price etc.

Keith
 
in my code please change this function as shown. it was a hang-over from an album based solution i wrote:
Code:
function displayUploadForm($msg=NULL){
    $maxsize = MAXFILESIZE;
    $msg = (empty($msg)) ? NULL: '<div class="errorMessage">'.$msg.'</div>';
    $shortdescription = (isset($_POST['shortdescripton'])) ? $_POST['shortdescripton'] : '';
    $contentObject = <<<HTML
$msg
<form method="post" action="{$_SERVER['PHP_SELF']}" enctype="multipart/form-data" >
<fieldset>
    <legend>Upload images</legend>
    <p>You can upload gif, png or jpegs either singly or in bulk as a zip file</p>
    Choose file (max $maxsize): <input type="file" name="upload" /><br/>
    Short description: <input type="text" maxlength="255" name="shortdescription" value="$shortdescription" /><br/>
    [red][s]Which album: $select[/s][/red]
    <input type="submit" name="submit" value="Upload" />
    <input type="hidden" name="action" value="uploadfile" />
</fieldset>
</form>
HTML;
    echo $contentObject;
}
 
Your zip file upload looks good and it have validations too...! But I am looking for multifile image upload. The user need to upload 4 or 5 images at a time.

I am able to do only one image upload. If you have any example to upload multiple images can you please provide that.

Thanks a lot in Advance...!

Thanks,
SB
 
i told you how to do this in my first post. use arrays.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top