Hi,
I use a upload form to upload images first in a server directory and then I would like to save file in a database.

My questions :
1. I would like to change the name that image is saved like that :
Image_1.jpeg or Image_1.gif whatever type.

2. I need to save in a database table

table images{
id
name_image
type_image
size
}

Could someone help me ???

Please

Recommended Answers

All 9 Replies

change the upload.php as -

<?php  

// filename: upload.processor.php

// first let's set some variables

// make a note of the current working directory, relative to root.
$directory_self = str_replace(basename($_SERVER['PHP_SELF']), '', $_SERVER['PHP_SELF']);

// make a note of the directory that will recieve the uploaded files
$uploadsDirectory = $_SERVER['DOCUMENT_ROOT'] . $directory_self . 'uploaded_files/';

// make a note of the location of the upload form in case we need it
$uploadForm = 'http://' . $_SERVER['HTTP_HOST'] . $directory_self . 'upload.form.php';

// make a note of the location of the success page
$uploadSuccess = 'http://' . $_SERVER['HTTP_HOST'] . $directory_self . 'upload.success.php';

// name of the fieldname used for the file in the HTML form
$fieldname = 'file';



// Now let's deal with the upload

// possible PHP upload errors
$errors = array(1 => 'php.ini max file size exceeded', 
                2 => 'html form max file size exceeded', 
                3 => 'file upload was only partial', 
                4 => 'no file was attached');

// check the upload form was actually submitted else print form
isset($_POST['submit'])
	or error('the upload form is neaded', $uploadForm);

// check for standard uploading errors
($_FILES[$fieldname]['error'] == 0)
	or error($errors[$_FILES[$fieldname]['error']], $uploadForm);
	
// check that the file we are working on really was an HTTP upload
@is_uploaded_file($_FILES[$fieldname]['tmp_name'])
	or error('not an HTTP upload', $uploadForm);
	
// validation... since this is an image upload script we 
// should run a check to make sure the upload is an image
@getimagesize($_FILES[$fieldname]['tmp_name'])
	or error('only image uploads are allowed', $uploadForm);
	
// make a unique filename for the uploaded file and check it is 
// not taken... if it is keep trying until we find a vacant one
$now = time();
/************Calculate the new file name**********/
//conection to the db
$con  = mysql_connect($host,$userName,$passwd);
$query = "select max(id) from tblName";
$queryExec = mysql_query($query);
while($row = mysql_fetch_array($queryExec))
{
	$LAST_IMAGE_ID = $row['id'];
}
//$newFileName = $uploadsDirectory.$now.'-'.$_FILES[$fieldname]['name']);
$uploadFilename = $_FILES[$fieldname]['name'].'_'.$LAST_IMAGE_ID;
/*
while(file_exists($uploadFilename = $uploadsDirectory.$now.'-'.$_FILES[$fieldname]['name']))
{
	$now++;
}
*/
// now let's move the file to its final and allocate it with the new filename
@move_uploaded_file($_FILES[$fieldname]['tmp_name'], $uploadFilename)
	or error('receiving directory insuffiecient permission', $uploadForm);
	
// If you got this far, everything has worked and the file has been successfully saved.
// We are now going to redirect the client to the success page.
header('Location: ' . $uploadSuccess);

// make an error handler which will be used if the upload fails
function error($error, $location, $seconds = 5)
{
	header("Refresh: $seconds; URL=\"$location\"");
	echo '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"'."\n".
	'"http://www.w3.org/TR/html4/strict.dtd">'."\n\n".
	'<html lang="en">'."\n".
	'	<head>'."\n".
	'		<meta http-equiv="content-type" content="text/html; charset=iso-8859-1">'."\n\n".
	'		<link rel="stylesheet" type="text/css" href="stylesheet.css">'."\n\n".
	'	<title>Upload error</title>'."\n\n".
	'	</head>'."\n\n".
	'	<body>'."\n\n".
	'	<div id="Upload">'."\n\n".
	'		<h1>Upload failure</h1>'."\n\n".
	'		<p>An error has occured: '."\n\n".
	'		<span class="red">' . $error . '...</span>'."\n\n".
	'	 	The upload form is reloading</p>'."\n\n".
	'	 </div>'."\n\n".
	'</html>';
	exit;
} // end error handler

?>

You will need to create the database connection and modify the select query to get the id of the last image entry from the table where you saving images.

change the upload.php as -

<?php  

// filename: upload.processor.php

// first let's set some variables

// make a note of the current working directory, relative to root.
$directory_self = str_replace(basename($_SERVER['PHP_SELF']), '', $_SERVER['PHP_SELF']);

// make a note of the directory that will recieve the uploaded files
$uploadsDirectory = $_SERVER['DOCUMENT_ROOT'] . $directory_self . 'uploaded_files/';

// make a note of the location of the upload form in case we need it
$uploadForm = 'http://' . $_SERVER['HTTP_HOST'] . $directory_self . 'upload.form.php';

// make a note of the location of the success page
$uploadSuccess = 'http://' . $_SERVER['HTTP_HOST'] . $directory_self . 'upload.success.php';

// name of the fieldname used for the file in the HTML form
$fieldname = 'file';



// Now let's deal with the upload

// possible PHP upload errors
$errors = array(1 => 'php.ini max file size exceeded', 
                2 => 'html form max file size exceeded', 
                3 => 'file upload was only partial', 
                4 => 'no file was attached');

// check the upload form was actually submitted else print form
isset($_POST['submit'])
	or error('the upload form is neaded', $uploadForm);

// check for standard uploading errors
($_FILES[$fieldname]['error'] == 0)
	or error($errors[$_FILES[$fieldname]['error']], $uploadForm);
	
// check that the file we are working on really was an HTTP upload
@is_uploaded_file($_FILES[$fieldname]['tmp_name'])
	or error('not an HTTP upload', $uploadForm);
	
// validation... since this is an image upload script we 
// should run a check to make sure the upload is an image
@getimagesize($_FILES[$fieldname]['tmp_name'])
	or error('only image uploads are allowed', $uploadForm);
	
// make a unique filename for the uploaded file and check it is 
// not taken... if it is keep trying until we find a vacant one
$now = time();
/************Calculate the new file name**********/
//conection to the db
$con  = mysql_connect($host,$userName,$passwd);
$query = "select max(id) from tblName";
$queryExec = mysql_query($query);
while($row = mysql_fetch_array($queryExec))
{
	$LAST_IMAGE_ID = $row['id'];
}
//$newFileName = $uploadsDirectory.$now.'-'.$_FILES[$fieldname]['name']);
$uploadFilename = $_FILES[$fieldname]['name'].'_'.$LAST_IMAGE_ID;
/*
while(file_exists($uploadFilename = $uploadsDirectory.$now.'-'.$_FILES[$fieldname]['name']))
{
	$now++;
}
*/
// now let's move the file to its final and allocate it with the new filename
@move_uploaded_file($_FILES[$fieldname]['tmp_name'], $uploadFilename)
	or error('receiving directory insuffiecient permission', $uploadForm);
	
// If you got this far, everything has worked and the file has been successfully saved.
// We are now going to redirect the client to the success page.
header('Location: ' . $uploadSuccess);

// make an error handler which will be used if the upload fails
function error($error, $location, $seconds = 5)
{
	header("Refresh: $seconds; URL=\"$location\"");
	echo '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"'."\n".
	'"http://www.w3.org/TR/html4/strict.dtd">'."\n\n".
	'<html lang="en">'."\n".
	'	<head>'."\n".
	'		<meta http-equiv="content-type" content="text/html; charset=iso-8859-1">'."\n\n".
	'		<link rel="stylesheet" type="text/css" href="stylesheet.css">'."\n\n".
	'	<title>Upload error</title>'."\n\n".
	'	</head>'."\n\n".
	'	<body>'."\n\n".
	'	<div id="Upload">'."\n\n".
	'		<h1>Upload failure</h1>'."\n\n".
	'		<p>An error has occured: '."\n\n".
	'		<span class="red">' . $error . '...</span>'."\n\n".
	'	 	The upload form is reloading</p>'."\n\n".
	'	 </div>'."\n\n".
	'</html>';
	exit;
} // end error handler

?>

You will need to create the database connection and modify the select query to get the id of the last image entry from the table where you saving images.

Thanks a lot for your help!!!

Wait change the code at line 59 by -

$LAST_IMAGE_ID = $row['id'];
	$next_img_id = $LAST_IMAGE_ID+1; 
}
//$newFileName = $uploadsDirectory.$now.'-'.$_FILES[$fieldname]['name']);
$uploadFilename = $_FILES[$fieldname]['name'].'_'.$next_img_id ;

I try but it does not work to me.
First of all the image is not saved in directory uploades_images but in root directory.
And then my database is empty.

How would some third person will know your directory structure, unless you mention it here.
change -

// make a note of the directory that will recieve the uploaded files
$uploadsDirectory = $_SERVER['DOCUMENT_ROOT'] . $directory_self . 'uploades_images/';
//$newFileName = $uploadsDirectory.$now.'-'.$_FILES[$fieldname]['name']);
$uploadFilename = $uploadsDirectory.$_FILES[$fieldname]['name'].'_'.$LAST_IMAGE_ID;

I don't understand what am I doing wrong.

my database :

mysql> create database images;
Query OK, 1 row affected (0.02 sec)

mysql> use images;
Database changed
mysql> create table t(
    -> id int(4),
    -> name varchar(30));
Query OK, 0 rows affected (0.11 sec)

mysql> select * from t;
Empty set (0.00 sec)

My file upload_processor.php :

<?php  
$directory_self = str_replace(basename($_SERVER['PHP_SELF']), '', $_SERVER['PHP_SELF']);
$uploadsDirectory = 'uploades_files';
$uploadForm = 'upload.form.php';
$uploadSuccess = 'upload.success.php';
$fieldname = 'file';

$errors = array(1 => 'php.ini max file size exceeded', 
                2 => 'html form max file size exceeded', 
                3 => 'file upload was only partial', 
                4 => 'no file was attached');


isset($_POST['submit'])
	or error('the upload form is neaded', $uploadForm);


($_FILES[$fieldname]['error'] == 0)
	or error($errors[$_FILES[$fieldname]['error']], $uploadForm);
	

@is_uploaded_file($_FILES[$fieldname]['tmp_name'])
	or error('not an HTTP upload', $uploadForm);
	
@getimagesize($_FILES[$fieldname]['tmp_name'])
	or error('only image uploads are allowed', $uploadForm);
	

$con  = mysql_connect("localhost","root","");
mysql_select_db("images",$con);
$query = "select max(id) from t";
$queryExec = mysql_query($query);

while($row = mysql_fetch_array($queryExec))
{
      $LAST_IMAGE_ID = $row['id'];
      $next_img_id = $LAST_IMAGE_ID+1;
      }
   
     $uploadFilename = $uploadsDirectory.$_FILES[$fieldname]['name'].'_'.$LAST_IMAGE_ID;

@move_uploaded_file($_FILES[$fieldname]['tmp_name'], $uploadFilename)
	or error('receiving directory insuffiecient permission', $uploadForm);
	
header('Location: ' . $uploadSuccess);

function error($error, $location, $seconds = 5)
{
	header("Refresh: $seconds; URL=\"$location\"");
	echo '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"'."\n".
	'"http://www.w3.org/TR/html4/strict.dtd">'."\n\n".
	'<html lang="en">'."\n".
	'	<head>'."\n".
	'		<meta http-equiv="content-type" content="text/html; charset=iso-8859-1">'."\n\n".
	'		<link rel="stylesheet" type="text/css" href="stylesheet.css">'."\n\n".
	'	<title>Upload error</title>'."\n\n".
	'	</head>'."\n\n".
	'	<body>'."\n\n".
	'	<div id="Upload">'."\n\n".
	'		<h1>Upload failure</h1>'."\n\n".
	'		<p>An error has occured: '."\n\n".
	'		<span class="red">' . $error . '...</span>'."\n\n".
	'	 	The upload form is reloading</p>'."\n\n".
	'	 </div>'."\n\n".
	'</html>';
	exit;
} 
?>

I am very very sorry for my questions but I am trying to learn.

/************Calculate the new file name**********/
//conection to the db
$db = "images";
$host;
$userName = 'admin';
$passwd = '';
$con  = mysql_connect($host,$userName,$passwd);
mysql_select_db($db);
$query = "select max(id) from t";
$queryExec = mysql_query($query);
while($row = mysql_fetch_array($queryExec))
{
	$LAST_IMAGE_ID = $row['id'] ;
	$img_id = $LAST_IMAGE_ID+1;
}
//$newFileName = $uploadsDirectory.$now.'-'.$_FILES[$fieldname]['name']);
$uploadFilename = $uploadsDirectory.$_FILES[$fieldname]['name'].'_'.$img_id ;
/*
while(file_exists($uploadFilename = $uploadsDirectory.$now.'-'.$_FILES[$fieldname]['name']))
{
	$now++;
}
*/
// now let's move the file to its final and allocate it with the new filename
@move_uploaded_file($_FILES[$fieldname]['tmp_name'], $uploadFilename)
	or error('receiving directory insuffiecient permission', $uploadForm);

$query = "insert into t(name) values ('".$uploadFilename."'";
$queryExec = mysql_query($query);

change the table structure to -

mysql> drop t
mysql> create table t(
id int(4) NOT NULL AUTO_INCREMENT, PRIMARY KEY(keywords_id),
name varchar(30)
)

Thanks for all!!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.