6 Replies - 1855 Views - Last Post: 25 November 2012 - 12:56 PM Rate Topic: -----

#1 streamland  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 5
  • Joined: 15-November 12

Why duplicate data to db using foreach

Posted 15 November 2012 - 07:00 AM

The code bellow sending data to the table but repeat it as shown bellow.

$i      = 1;
$cols = array();
$data = array();
// now let's move the file to its final and allocate it with the new filename
foreach($active_keys as $key)
{
@move_uploaded_file($_FILES[$fieldname]['tmp_name'][$key], $uploadFilename[$key])
  or error('receiving directory insuffiecient permission', $uploadForm);
                          
$cols[] = "image" . $i++;
                $data[] = basename($uploadFilename[$key]);
}
  
$cols =  array_map ('mysql_real_escape_string', $cols);
$data=  array_map ('mysql_real_escape_string', $data);
  $query = 'INSERT INTO `imloop` (' . implode(', ', $cols) . ') VALUES ("' . implode('", "', $data) . '")';
 
  mysql_query($query) or exit($query . '<br />' . mysql_error());



INSERT INTO `imloop` (`id`, `image1`, `image2`, `image3`, `image4`, `image5`, `image6`) VALUES
(1, '1352903903-1.jpg', 1352903903, 1352903903, 1352903903, 1352903903, 1352903903);




or

INSERT INTO `imloop` (`id`, `image1`, `image2`, `image3`, `image4`, `image5`, `image6`) VALUES
(1, '1352903903-1.jpg', 1352903903, 1352903903, 1352903903, 1352903903, 1352903903),  // here I tried to upload 6 different images
(2, '1352904073-6.jpg', 1352904073, 0, 0, 0, 0),                                                                                                                                                                           // here I tried to upload 2 different images
(3, '1352904279-1.jpg', 1352904279, 1352904279, 0, 0, 0),                                                                                                                                 // here I tried to upload 3 different images
(4, '1352904587-1.jpg', 1352904587, 1352904587, 0, 0, 0);




why it locate just first image I am putting in and repeat it to the `image2`, `image3`, `image4`, `image5`, `image6` .
and doesn't show others I am adding.

Is This A Good Question/Topic? 0
  • +

Replies To: Why duplicate data to db using foreach

#2 JackOfAllTrades  Icon User is offline

  • Saucy!
  • member icon

Reputation: 6092
  • View blog
  • Posts: 23,614
  • Joined: 23-August 08

Re: Why duplicate data to db using foreach

Posted 15 November 2012 - 07:43 AM

Time to start debugging!

What is the content of $active_keys prior to the foreach loop? Use print_r to find out.
Was This Post Helpful? 0
  • +
  • -

#3 streamland  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 5
  • Joined: 15-November 12

Re: Why duplicate data to db using foreach

Posted 15 November 2012 - 11:41 AM

The code look likes bellow

<?php  
// filename: upload.processor.php
// first let's set some variables
include("conf.php");
  // open database connection
		$connection = mysql_connect($host, $user, $pass) or die ("Unable to connect!");
		//$db = mysql_connect($host, $user, $pass) or die ("Unable to connect!");
		
  // select database
		mysql_select_db($db) or die ("Unable to select database!");


// 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 . 'multiple.upload.form.php';

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

// name of the fieldname used for the file in the HTML form
$fieldname = 'file';
//echo'<pre>';print_r($_FILES);exit;
// Now let's deal with the uploaded files

// 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 if any files were uploaded and if 
// so store the active $_FILES array keys
$active_keys = array();
foreach($_FILES[$fieldname]['name'] as $key => $filename)
{
	if(!empty($filename))
	{
		$active_keys[] = $key;
	}
}
// check at least one file was uploaded
count($active_keys)
	or error('No files were uploaded', $uploadForm);
		// check for standard uploading errors
foreach($active_keys as $key)
{
	($_FILES[$fieldname]['error'][$key] == 0)
		or error($_FILES[$fieldname]['tmp_name'][$key].': '.$errors[$_FILES[$fieldname]['error'][$key]], $uploadForm);
}
// check that the file we are working on really was an HTTP upload
foreach($active_keys as $key)
{
	@is_uploaded_file($_FILES[$fieldname]['tmp_name'][$key])
		or error($_FILES[$fieldname]['tmp_name'][$key].' 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
foreach($active_keys as $key)
{
	@getimagesize($_FILES[$fieldname]['tmp_name'][$key])
		or error($_FILES[$fieldname]['tmp_name'][$key].' not an image', $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
foreach($active_keys as $key)
{
	$now = time();
	while(file_exists($uploadFilename[$key] = $uploadsDirectory.$now.'-'.$_FILES[$fieldname]['name'][$key]))
	{
		$now++;		
	}
}
   $i    = 1;
$cols = array();
$data = array();
// now let's move the file to its final and allocate it with the new filename
foreach($active_keys as $key)
{
	@move_uploaded_file($_FILES[$fieldname]['tmp_name'][$key], $uploadFilename[$key])
		or error('receiving directory insuffiecient permission', $uploadForm);
	              
$cols[] = "image" . $i++;  //<-- note that I removed the comma
        $data[] = basename($uploadFilename[$key]);  //<-- note that I removed the quotes				  			
	} 	
$cols =  array_map ('mysql_real_escape_string', $cols);  
$data=  array_map ('mysql_real_escape_string', $data);
		$query = 'INSERT INTO `imloop` (' . implode(', ', $cols) . ') VALUES ("' . implode('", "', $data) . '")';
		
		mysql_query($query) or exit($query . '<br />' . mysql_error()); 
					
// 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);
mysql_close($connection);

// 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".
	'<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

?>


Was This Post Helpful? 0
  • +
  • -

#4 JackOfAllTrades  Icon User is offline

  • Saucy!
  • member icon

Reputation: 6092
  • View blog
  • Posts: 23,614
  • Joined: 23-August 08

Re: Why duplicate data to db using foreach

Posted 15 November 2012 - 02:38 PM

We really didn't need to see all of your pretty much copy/paste code.

You need to do the basic debugging I've already pointed out. Find out what the values of $active_keys, and probably $_FILES are on submit.
Was This Post Helpful? 1
  • +
  • -

#5 streamland  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 5
  • Joined: 15-November 12

Re: Why duplicate data to db using foreach

Posted 23 November 2012 - 06:33 AM

At last I could send image to directory and path to the db :rolleyes: but now I can't veiw the image it just shows X insted of picture.

id Image1 Image2 Image3 Image4 Image5 Image6
37 X X X X X X
38 X X X X X X

include ("conf.php");

	//$objConnect = mysql_connect("localhost","uploaddb","root") or die(mysql_error());
	$objConnect = mysql_connect($host, $user, $pass) or die(mysql_error());
	
	$objDB = mysql_select_db("imageloop");
	$strSQL = "SELECT * FROM imloop";
 $objQuery = mysql_query($strSQL) or die ("Error Query [".$strSQL."]");
?>
<table width="200" border="1">
<tr>
<th width="50"> <div align="center">id </div></th>
<th width="150"> <div align="center">Image1 </div></th>
<th width="150"> <div align="center">Image2 </div></th>
<th width="150"> <div align="center">Image3 </div></th>
<th width="150"> <div align="center">Image4 </div></th>
<th width="150"> <div align="center">Image5 </div></th>
<th width="150"> <div align="center">Image6 </div></th>
</tr>
<?
	while($objResult = mysql_fetch_array($objQuery))
	{
?>
<tr>
<td><div align="center"><?=$objResult['id'];?></div></td>

<td><img src="uploaded_files/<?=$objResult["Image1"];?>" border="1"></a></center></td>
<td><img src="uploaded_files/<?=$objResult["Image2"];?>" border="0"></a></center></td>
<td><img src="uploaded_files/<?=$objResult["Image3"];?>" border="0"></a></center></td>
<td><img src="uploaded_files/<?=$objResult["Image4"];?>" border="0"></a></center></td>
<td><img src="uploaded_files/<?=$objResult["Image5"];?>" border="0"></a></center></td>
<td><img src="uploaded_files/<?=$objResult["Image6"];?>" border="0"></a></center></td>

</tr>

<?
	}
?>
</table>
<?
print mysql_error();
mysql_close($objConnect);
?>

Was This Post Helpful? 0
  • +
  • -

#6 streamland  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 5
  • Joined: 15-November 12

Re: Why duplicate data to db using foreach

Posted 23 November 2012 - 08:03 AM

Thanks a lot the problem was solved :rolleyes:
Was This Post Helpful? 0
  • +
  • -

#7 streamland  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 5
  • Joined: 15-November 12

Re: Why duplicate data to db using foreach

Posted 25 November 2012 - 12:56 PM

I appreciate for help I could get it work. The path goes to db and the I can weiw it.

But also I'd like by the way thambnail the images and locate path the same way .
image1 image2 image3 image4 image5 image6 image_small1 image_small2 image_small3 image_small4 image_small5 image_small6

I've got the thambnail script which I would like to implement here
Could you help me please to do it

$i    = 1;
$sm = 1;
$images_sm = "thumbnails_"$uploadFilename[$key];
// now let's move the file to its final and allocate it with the new filename
foreach($active_keys as $key)
{ 
	@move_uploaded_file($_FILES[$fieldname]['tmp_name'][$key],$uploadFilename[$key])
		or error('receiving directory insuffiecient permission', $uploadForm);
	              
$cols[] = "image" . $i++;  //<-- note that I removed the comma       
$cols_sm[] = "image_small" . $sm++;

		$data[] = "'" . basename($uploadFilename[$key]) . "'";
		//-----------------------------------------------------------------------------------------------------
		$width=100; //*** Fix Width & Heigh (Autu caculate) ***//
			//$size=GetimageSize($images);
			$size=GetimageSize($uploadFilename[$key]);
			$height=round($width*$size[1]/$size[0]);
			$images_orig = ImageCreateFromJPEG($uploadFilename[$key]);
			$photoX = ImagesX($images_orig);   // получаем ширину
			$photoY = ImagesY($images_orig);   // а здесь высоту
			$images_fin = ImageCreateTrueColor($width, $height);       
			ImageCopyResampled($images_fin, $images_orig, 0, 0, 0, 0, $width+1, $height+1, $photoX, $photoY);
			ImageJPEG($images_fin,"uploaded_files/".$images_sm);
			ImageDestroy($images_orig);
			ImageDestroy($images_fin);
			
		//	--------------------------------------------------------------------------------------------------------------
		
		$data_sm[] = "'" . basename($uploadFilename[$key]) . "'";
		
	} 	
$query = 'INSERT INTO `imloop` (' . implode(', ', $cols) . ' , ' . implode(', ', $cols_sm) . ') 

                                           VALUES (' . implode(', ', $data) . ' ,  ' . implode(', ', $data_sm) . ')';


Was This Post Helpful? 0
  • +
  • -

Page 1 of 1