Jump to content

Insert Multiple Filename into DB after upload


StefanRSA

Recommended Posts

Hi,

 

I had a problem with image uploads. All work fine, but I am not sure how to insert the image names into a DB into one row entry... I have the ode and would like anybody to please tell me how I can do this. At this moment, the code is working but enter the image names each into a new DB entry....

<?
//Dave Hewards image script
// Include the config files
include '../incl/config.php';
// Include the header php
include '../header/header.php'; 
function resize($img, $thumb_width, $newfilename)
{
$max_width=$thumb_width;



//Get Image size info
list($width_orig, $height_orig, $image_type) = getimagesize($img);

switch ($image_type)
{
case 1: $im = imagecreatefromgif($img); break;
case 2: $im = imagecreatefromjpeg($img);  break;
case 3: $im = imagecreatefrompng($img); break;
default:  trigger_error('Unsupported filetype!', E_USER_WARNING);  break;
}

/*** calculate the aspect ratio ***/
$aspect_ratio = (float) $height_orig / $width_orig;

/*** calculate the thumbnail width based on the height ***/
$thumb_height = round($thumb_width * $aspect_ratio);

while($thumb_height>$max_width)
{
$thumb_width-=10;
$thumb_height = round($thumb_width * $aspect_ratio);
}

$newImg = imagecreatetruecolor($thumb_width, $thumb_height);

/* Check if this image is PNG or GIF, then set if Transparent*/
if(($image_type == 1) OR ($image_type==3))
{
imagealphablending($newImg, false);
imagesavealpha($newImg,true);
$transparent = imagecolorallocatealpha($newImg, 255, 255, 255, 127);
imagefilledrectangle($newImg, 0, 0, $thumb_width, $thumb_height, $transparent);
}
imagecopyresampled($newImg, $im, 0, 0, 0, 0, $thumb_width, $thumb_height, $width_orig, $height_orig);

//Generate the file, and rename it to $newfilename
switch ($image_type)
{
case 1: imagegif($newImg,$newfilename); break;
case 2: imagejpeg($newImg,$newfilename);  break;
case 3: imagepng($newImg,$newfilename); break;
default:  trigger_error('Failed resize image!', E_USER_WARNING);  break;
}

return $newfilename;
}
?>
<?
////////////////////////////////////////////////////////////////////////////////
//This stuff is outside of the function. It operates with our images
if(isset($_POST['submitimages'])){
$success=0;
$imgNumb=1; //This the "pointer" to images
$DestinationDir="../ad_images/";  //Place the destination dir here
$ThumbDir="/thumb/";  //Place the thumb dir here

do{
if($_FILES["img$imgNumb"][tmp_name]!=''){
$success++;
$Unique=microtime(); // We want unique names, right?
$destination=$DestinationDir.md5($Unique).".jpg";
$thumb=$ThumbDir.md5($Unique).".jpg";

$IMG=getimagesize($_FILES["img$imgNumb"][tmp_name]);
$finalimage = resize($_FILES["img$imgNumb"][tmp_name], 250, $destination);
//use the filename variable below to record the image name entered so that you can then use this variable to update your database if

$filename = md5($Unique).".jpg";

$field = 'img'.$imgNumb;

//mysql update your database fields

$query = mysql_query("INSERT INTO ad_image (image_1) 
  VALUES ('$filename')") or die(mysql_error());

}

$imgNumb++;
} while($_FILES["img$imgNumb"][name]);

if($success>=1){
$message = "Images uploaded!";

}
else {echo "We might have a problem???";}
}

?>
<form action="" method="post" enctype="multipart/form-data" >
<table width="300px"><tr><Th colspan="3">Change Profile Images: </TH></tr>
<tr><td>Image 1:</td><td><input type="file" name="img1"></td></tr>
<tr><td>Image 2:</td><td><input type="file" name="img2"></td></tr>
<tr><td>Image 3:</td><td><input type="file" name="img3"></td></tr>
<tr><td>Image 4:</td><td><input type="file" name="img4"></td></tr>
<tr><Td colspan="2" align="right"><input type="submit" name="submitimages" class="submitlarge" value="Upload profile images"></TD></tr></table>
</form>

 

With :

$query = mysql_query("INSERT INTO ad_image (image_1) 
  VALUES ('$filename')") or die(mysql_error());

the images is inserted into the DB but each on its own row.

I would like to add All images in one DB entry or row....

 

How should I do this?

 

THANKS

???

Link to comment
Share on other sites

Basically I want to doe the following:

$query = mysql_query("INSERT INTO ad_image (image_1, image_2, image_3, image_4)
  VALUES ('$filename[0]', '$filename[1]', '$filename[2]', '$filename[3]', )") or die(mysql_error());

but the way it is written now will it only give me the 1st, 2nd, 3rd and 4th letter of the filename in the entry....

 

Please help....

Link to comment
Share on other sites

aviavi, I am creating new images and only save the newly named images to a folder.

It is those names that I want to put into the DB so I can re-call them later. I dump the original images and will help me nothing...

Thanks for your help anyway...

Link to comment
Share on other sites

When you leave the action empty it just posts back to the current page.

 

only give me the 1st, 2nd, 3rd and 4th letter of the filename in the entry....

 

Letter? Was that a typo?

 

Are you saying you want to enter all 4 of the images into one single row, as apposed to a row each? If so then you'll need to build the SQL up as a string and then run the query after the loop.

 

Make sense?

 

Link to comment
Share on other sites

What I meant was that its putting the $filename into an array (I Think) and its not what I want...

MrAdam, can you please please give me an example on how I should do this???

 

I am getting 100% confused at this moment...

 

Thanks

Link to comment
Share on other sites

Using $_FILES['img$imgNumb'][name] would be trying to find the literal index "img$imgNumb" in the array for each loop, not "img1", "img2", etc. Though *personally* I'd still go for single quotes and using the dot to concat the $imgNumb var (like: 'img' . $imgNumb)

 

You think you want them in an array? What for? Really you already have them in an array...

 

What exactly is the desired outcome of the script?

Link to comment
Share on other sites

Sorry if i confuse you guys...

I have a form with 4 fields to upload images:

<input type="file" name="img1">

<input type="file" name="img2">

<input type="file" name="img3">

<input type="file" name="img4">

 

On submit the images is uploaded, resized renamed and saved into a folder.

I need these new names to be entered into a MySql DB where all the other data of the form is placed so if I link to the submitted form I will be able to collect the image names from the DB and display it on the form again...

Link to comment
Share on other sites

At this stage its just like:

-- Table structure for table `ad_image`
--

CREATE TABLE IF NOT EXISTS `ad_image` (
  `id` int(11) NOT NULL auto_increment,
  `ad` varchar(50) NOT NULL,
  `image_1` varchar(50) NOT NULL,
  `image_2` varchar(50) NOT NULL,
  `image_3` varchar(50) NOT NULL,
  `image_4` varchar(50) NOT NULL,
  PRIMARY KEY  (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=35 ;

--
-- Dumping data for table `ad_image`
--

INSERT INTO `ad_image` (`id`, `ad`, `image_1`, `image_2`, `image_3`, `image_4`) VALUES
(34, '', 'ffbba98b126bb7669aa6ad77222426b5.jpg', '', '', '');

Link to comment
Share on other sites

Okay I see now, where do you get the value for the `ad` field?

 

What I was talking about before is building the query up through the code, rather than running a query for each iteration of the loop - obviously creating 4 rows. I don't have the time to get into all your code right now, but consider something like:

 

$insert_sql = "insert into ad_image (ad, image_1, image_2, image_3, image_4) values ('', ";

for (loop condition) {
    $insert_sql .= "'" . $filename . "',";
}

$insert_sql = rtrim($insert_sql, ','); // trim the last comma

$insert_sql .= ")";

$insert_query = mysql_query($insert_sql);

 

Sorry if it's too vague..

Link to comment
Share on other sites

Mr Adam.

 

I have a problem with your solution. Nothing gets uploaded and I dont even get a error with or die(mysql_error());... I am sure I am not putting your example in the correct position on the form...

 

Is it possible to have a look at my code and tell me where exactly I should put it in? Thanks...

 

My code as it is now:

if(isset($_POST['submitimages'])){
$im1= $_POST['img1'];
$im2= $_POST['img2'];
$im3= $_POST['img3'];
$im4= $_POST['img4'];
$success=0;
$imgNumb=1; //This the "pointer" to images
$DestinationDir="../ad_images/";  //Place the destination dir here
$ThumbDir="/thumb/";  //Place the thumb dir here

do{
$insert_sql = "insert into ad_image (ad, image_1, image_2, image_3, image_4) values ('', ";
if($_FILES["img$imgNumb"][tmp_name]!=''){
$success++;
$Unique=microtime(); // We want unique names, right?
$destination=$DestinationDir.md5($Unique).".jpg";
$thumb=$ThumbDir.md5($Unique).".jpg";

$IMG=getimagesize($_FILES["img$imgNumb"][tmp_name]);
$finalimage = resize($_FILES["img$imgNumb"][tmp_name], 250, $destination);
//use the filename variable below to record the image name entered so that you can then use this variable to update your database if

$filename = md5($Unique).".jpg";

$field = 'img'.$imgNumb;

//mysql update your database fields
$insert_sql .= "'" . $filename . "',";
//$query = mysql_query("INSERT INTO ad_image (image_1) 
//  VALUES ('$filename')") or die(mysql_error());
}
$insert_sql = rtrim($insert_sql, ','); // trim the last comma

$insert_sql .= ")";

$insert_query = mysql_query($insert_sql) or die(mysql_error());;
$imgNumb++;
} while($_FILES["img$imgNumb"][name]);

if($success>=1){
$message = "Images uploaded!";

}
else {echo "We might have a problem???";}
echo $im1;
echo $im2;
echo $im3;
echo $im4;
}

Link to comment
Share on other sites

The easiest way I could think of handling this would be as follows:

 

$insert_fields = "ad";
$insert_values = "''";

for($i = 1; $i <= 4; $i++) // You'd have to know how many images can be uploaded in advance this could be passed as another $_POST variable
{
if($_FILES["img" . $i][tmp_name]!='')
{
	// Do your processing stuff here

	$insert_fields .= ", image_" . $i;
	$insert_values .= ", '" . $filename . "'";
}
}

$insert_sql = "insert into ad_image (" . $insert_fields . ") VALUES (" . $insert_values . ")";

Link to comment
Share on other sites

Even better would be to change the loop to:

 

foreach ($_FILES as $key => $file)

 

You could then access the file properties with $file['tmp_name'] for example, or if you prefer $_FILES[$key]['tmp_name'] ...

 

.. Your way of building the query is better though!

Link to comment
Share on other sites

The way you're looping through the files could be improved. See if this works (obviously not tested it):

 

if(isset($_POST['submitimages']))
{
    $im1= $_POST['img1'];
    $im2= $_POST['img2'];
    $im3= $_POST['img3'];
    $im4= $_POST['img4'];
    $success=0;
    $DestinationDir="../ad_images/";  //Place the destination dir here
    $ThumbDir="/thumb/";  //Place the thumb dir here

    $insert_fields = '';
    $insert_values = '';

    foreach ($_FILES as $key => $file)
    {
        $Unique=microtime(); // We want unique names, right?
        $destination=$DestinationDir.md5($Unique).".jpg";
        $thumb=$ThumbDir.md5($Unique).".jpg";

        $IMG=getimagesize($file['tmp_name']);
        $finalimage = resize($file['tmp_name'], 250, $destination);
        //use the filename variable below to record the image name entered so that you can then use this variable to update your database if
        $filename = md5($Unique).".jpg";

        $insert_fields .= "image" . intval($key) . ",";
        $insert_values .= "'" . $filename . "',";
    }

    $insert_fields = rtrim($insert_fields, ',');
    $insert_values = rtrim($insert_values, ',');

    $insert_query = mysql_query("insert into ad_image (ad," . $insert_fields . ") values ('__advalue__'," . $insert_values . ")") or die(mysql_error());

    if($success>=1)
    {
        $message = "Images uploaded!";
    }

    else {echo "We might have a problem???";}
    echo $im1;
    echo $im2;
    echo $im3;
    echo $im4;
}

 

I just replaced where you'll need to put the value for the 'ad' field with "__advalue__" ...

Link to comment
Share on other sites

I think you have 'display errors' off, if it didn't pick up the syntax error from before. Try adding the following just after your first opening PHP tag:

 

error_reporting(E_ALL);
ini_set("display_errors", 1);

 

This will show you any errors occurring within the script.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.