Jump to content

multiple image upload


Don the dragon

Recommended Posts

Hi

I have a bit of a problem. I have a multiple image upload(12 images) section in my form. The problem is, is that when I submit to the database, I get 12 new entries in the database. What I want is for the DB to reflect 12 references of the images in one entry.

<?php require_once('../../Connections/propList.php'); ?>
<?php
if (!function_exists("GetSQLValueString")) {
function GetSQLValueString($theValue, $theType, $theDefinedValue = "", $theNotDefinedValue = "") 
{
  $theValue = get_magic_quotes_gpc() ? stripslashes($theValue) : $theValue;

  $theValue = function_exists("mysql_real_escape_string") ? mysql_real_escape_string($theValue) : mysql_escape_string($theValue);

  switch ($theType) {
    case "text":
      $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
      break;    
    case "long":
    case "int":
      $theValue = ($theValue != "") ? intval($theValue) : "NULL";
      break;
    case "double":
      $theValue = ($theValue != "") ? "'" . doubleval($theValue) . "'" : "NULL";
      break;
    case "date":
      $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
      break;
    case "defined":
      $theValue = ($theValue != "") ? $theDefinedValue : $theNotDefinedValue;
      break;
  }
  return $theValue;
}
}
if ((isset($_POST["MM_insert"])) && ($_POST["MM_insert"] == "form1")) {

// define a constant for the maximum upload size 
		define ('MAX_FILE_SIZE', 58000);
		if (array_key_exists('upload', $_POST)) {
	// define constant for upload folder
		define ('UPLOAD_DIR', 'upload/');
	//convert the maximum size to KB
		$max = number_format(MAX_FILE_SIZE/1024, 1).'KB';
	// create an array of permitted MIME types
		$permitted = array('image/gif','image/jpeg','image/pjpeg','image/png');
			foreach ($_FILES['image']['name'] as $number => $file) {
	// replace any spaces in orginal filename with undercores
		$file = str_replace(' ','_', $file);
	// begin by assuming the file is unacceptable 
		$sizeOK = false;
		$typeOK = false;
	//check that the file is within the permitted size 
		if ($_FILES['image']['size'][$number] > 0 || $_FILES['image']['size'][$number] <=
	  		MAX_FILE_SIZE) {
			$sizeOK = true;
	}
	//check that file is of a permitted MIME type
		foreach ($permitted as $type) {
			if ($type == $_FILES['image']['type'][$number]) {
			$typeOK = true;
			break;
		}
	}
		if ($sizeOK && $typeOK) {
		switch($_FILES['image']['error'][$number]) {
		case 0:
	// make sure file of same name does not already exist
		if (!file_exists(UPLOAD_DIR.$file)) {
	// move the file to the upload folder and rename it
		$success = move_uploaded_file($_FILES['image']['tmp_name'][$number], 
		UPLOAD_DIR.time().$file); 
		}
		else {
	// get the date and time
		ini_set('date.timezone','Europe/London');
		$now = date('Y-m-d-His');
		$success = move_uploaded_file($_FILES['image']['tmp_name'][$number], UPLOAD_DIR.$now.
		$file);
	}
		if ($success) {
			$result[] = "$file was successfully uploaded";
			}
		else {
			$result[] = "Error uploading $file. Please try again.";
			}
		break;
		case 3:
			$result[] = "Error uploading $file. Please try again.";
		default:
			$result[] = "";

			}
		}
		elseif ($_FILES['image']['error'][$number] == 4) {
			$result[] = 'No file was selected';
		}
		else {
			$result[] = "$file cannot be uploaded because the image size is too large. The Maximum size is $max.  Please re-size and try again.  Or you have an incorrect file type. Acceptable file types are gif, jpg, png.";
	}

  $insertSQL = sprintf("INSERT INTO sothebys (address, areas, bedrooms, bathrooms, garages, pool, security, property_type, facing, storey, waterfront, sole_mandate, floor_area, carport, levies_rates, garden, pets_allowed, recreational, prop_desc, price, image) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)",
                       GetSQLValueString($_POST['address'], "text"),
                       GetSQLValueString($_POST['areas'], "text"),
                       GetSQLValueString($_POST['bedrooms'], "int"),
                       GetSQLValueString($_POST['bathrooms'], "int"),
                       GetSQLValueString($_POST['garages'], "text"),
                       GetSQLValueString($_POST['pool'], "text"),
                       GetSQLValueString($_POST['security'], "text"),
                       GetSQLValueString($_POST['property_type'], "text"),
                       GetSQLValueString($_POST['facing'], "text"),
                       GetSQLValueString($_POST['storey'], "text"),
                       GetSQLValueString($_POST['waterfront'], "text"),
                       GetSQLValueString($_POST['sole_mandate'], "text"),
                       GetSQLValueString($_POST['floor_area'], "text"),
                       GetSQLValueString($_POST['carport'], "text"),
                       GetSQLValueString($_POST['levies_rates'], "text"),
                       GetSQLValueString($_POST['garden'], "text"),
                       GetSQLValueString($_POST['pets_allowed'], "text"),
                       GetSQLValueString($_POST['recreational'], "text"),
                       GetSQLValueString($_POST['prop_desc'], "text"),
                       GetSQLValueString($_POST['price'], "int"),
                       GetSQLValueString($file, "text"));

  mysql_select_db($database_propList, $propList);
  $Result1 = mysql_query($insertSQL, $propList) or die(mysql_error());
}
}
}

mysql_select_db($database_propList, $propList);
$query_propType = "SELECT * FROM proptype ORDER BY property_type";
$propType = mysql_query($query_propType, $propList) or die(mysql_error());
$row_propType = mysql_fetch_assoc($propType);
$totalRows_propType = mysql_num_rows($propType);

mysql_select_db($database_propList, $propList);
$query_getProp = "SELECT * FROM areas ORDER BY areas";
$getProp = mysql_query($query_getProp, $propList) or die(mysql_error());
$row_getProp = mysql_fetch_assoc($getProp);
$totalRows_getProp = mysql_num_rows($getProp);

mysql_select_db($database_propList, $propList);
$query_listProp = "SELECT * FROM sothebys";
$listProp = mysql_query($query_listProp, $propList) or die(mysql_error());
$row_listProp = mysql_fetch_assoc($listProp);
$totalRows_listProp = mysql_num_rows($listProp);
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Insert a new property</title>
</head>

<body>
<p>Insert a new property listing</p>
<form action="<?php echo $editFormAction; ?>" method="post" id="form1" enctype="multipart/form-data">
  <table>
    <tr valign="baseline">
      <td align="right">Address:</td>
      <td><input type="text" name="address" value="" size="32" /></td>
    </tr>
    <tr valign="baseline">
      <td align="right">Areas:</td>
      <td><select name="areas" id="areas">
        <option value="menuitem1" >Choose an area</option>
        <?php
do {  
?><option value="<?php echo $row_getProp['areas']?>"><?php echo $row_getProp['areas']?></option><?php
} while ($row_getProp = mysql_fetch_assoc($getProp));
  $rows = mysql_num_rows($getProp);
  if($rows > 0) {
      mysql_data_seek($getProp, 0);
  $row_getProp = mysql_fetch_assoc($getProp);
  }
?>
      </select>      </td>
    </tr>
    <tr valign="baseline">
      <td align="right">Property_type:</td>
      <td><select name="property_type" id="property_type">
        <option value="menuitem1" >Choose a property type</option>
        <?php
do {  
?><option value="<?php echo $row_propType['property_type']?>"><?php echo $row_propType['property_type']?></option>
        <?php
} while ($row_propType = mysql_fetch_assoc($propType));
  $rows = mysql_num_rows($propType);
  if($rows > 0) {
      mysql_data_seek($propType, 0);
  $row_propType = mysql_fetch_assoc($propType);
  }
?>
      </select>      </td>
    </tr>
    <tr valign="baseline">
      <td align="right">Price:</td>
      <td><input type="text" name="price" value="" size="32" /></td>
    </tr>
    <tr valign="baseline">
      <td align="right">Levies_rates:</td>
      <td><input type="text" name="levies_rates" value="" size="32" /></td>
    </tr>
    <tr valign="baseline">
      <td align="right">Floor_area:</td>
      <td><input type="text" name="floor_area" value="" size="32" /></td>
    </tr>
    <tr valign="baseline">
      <td align="right">Bedrooms:</td>
      <td><input type="text" name="bedrooms" value="" size="32" /></td>
    </tr>
    <tr valign="baseline">
      <td align="right">Bathrooms:</td>
      <td><input type="text" name="bathrooms" value="" size="32" /></td>
    </tr>
    <tr valign="baseline">
      <td align="right">Garages:</td>
      <td><input type="text" name="garages" value="" size="32" /></td>
    </tr>
    <tr valign="baseline">
      <td align="right">Facing:</td>
      <td><input type="text" name="facing" value="" size="32" /></td>
    </tr>
    <tr valign="baseline">
      <td align="right">Storey:</td>
      <td><input type="text" name="storey" value="" size="32" /></td>
    </tr>
    <tr valign="baseline">
      <td align="right">Carport:</td>
      <td><input type="text" name="carport" value="" size="32" /></td>
    </tr>
    <tr valign="baseline">
      <td align="right">Security:</td>
      <td valign="baseline"><table>
        <tr>
          <td>
          	<input  <?php if (!(strcmp($row_listProp['security'],"y"))) {echo "checked=\"checked\"";} ?> type="radio" name="security" value="y" />
            Yes
            <input  <?php if (!(strcmp($row_listProp['security'],"n"))) {echo "checked=\"checked\"";} ?> type="radio" name="security" value="n" checked="checked" />
            No          </td>
        </tr>
      </table></td>
    </tr>
    <tr valign="baseline">
      <td align="right">Waterfront:</td>
      <td valign="baseline"><table>
        <tr>
          <td>
          	<input  <?php if (!(strcmp($row_listProp['waterfront'],"y"))) {echo "checked=\"checked\"";} ?> type="radio" name="waterfront" value="y" />
            Yes
            <input  <?php if (!(strcmp($row_listProp['waterfront'],"n"))) {echo "checked=\"checked\"";} ?> type="radio" name="waterfront" value="n" checked="checked" />
            No          </td>
        </tr>
      </table></td>
    </tr>
    <tr valign="baseline">
      <td align="right">Pool:</td>
      <td valign="baseline"><table>
        <tr>
          <td>
          	<input  <?php if (!(strcmp($row_listProp['pool'],"y"))) {echo "checked=\"checked\"";} ?> type="radio" name="pool" value="y" />
            Yes
            <input  <?php if (!(strcmp($row_listProp['pool'],"n"))) {echo "checked=\"checked\"";} ?> type="radio" name="pool" value="n" checked="checked" />
            No          </td>
        </tr>
      </table></td>
    </tr>
    <tr valign="baseline">
      <td align="right">Garden:</td>
      <td valign="baseline"><table>
        <tr>
          <td>
          	<input  <?php if (!(strcmp($row_listProp['garden'],"y"))) {echo "checked=\"checked\"";} ?> type="radio" name="garden" value="y" />
            Yes
            <input  <?php if (!(strcmp($row_listProp['garden'],"n"))) {echo "checked=\"checked\"";} ?> type="radio" name="garden" value="n" checked="checked" />
            No          </td>
        </tr>
      </table></td>
    </tr>
    <tr valign="baseline">
      <td align="right">Pets_allowed:</td>
      <td valign="baseline"><table>
        <tr>
          <td>
          	<input  <?php if (!(strcmp($row_listProp['pets_allowed'],"y"))) {echo "checked=\"checked\"";} ?> type="radio" name="pets_allowed" value="y" />
            Yes
            <input  <?php if (!(strcmp($row_listProp['pets_allowed'],"n"))) {echo "checked=\"checked\"";} ?> type="radio" name="pets_allowed" value="n" checked="checked" />
            No          </td>
        </tr>
      </table></td>
    </tr>
    <tr valign="baseline">
      <td align="right">Sole_mandate:</td>
      <td valign="baseline"><table>
        <tr>
          <td>
          	<input  <?php if (!(strcmp($row_listProp['sole_mandate'],"y"))) {echo "checked=\"checked\"";} ?> type="radio" name="sole_mandate" value="y" />
            Yes
            <input  <?php if (!(strcmp($row_listProp['sole_mandate'],"n"))) {echo "checked=\"checked\"";} ?> type="radio" name="sole_mandate" value="n" checked="checked" />
            No          </td>
        </tr>
      </table></td>
    </tr>
    <tr valign="baseline">
      <td align="right">Recreational:</td>
      <td><input type="text" name="recreational" value="" size="32" /></td>
    </tr>
    <tr valign="baseline">
      <td align="right">Prop_desc:</td>
      <td><input type="text" name="prop_desc" value="" size="32" /></td>
    </tr>
    <tr valign="baseline">
      <td align="right">Upload up to 12 images:
          <label for="image">Upload image:</label>
          <input type="file" name="image[]" /><br/>
          <label for="image">Upload image:</label>
          <input type="file" name="image[]" /><br/>
          <label for="image">Upload image:</label>
          <input type="file" name="image[]" /><br/>
          <label for="image">Upload image:</label>
          <input type="file" name="image[]"/><br/>
          <label for="image">Upload image:</label>
          <input type="file" name="image[]"/><br/>
          <label for="image">Upload image:</label>
          <input type="file" name="image[]"/><br/>
          <label for="image">Upload image:</label>
          <input type="file" name="image[]"/><br/>
          <label for="image">Upload image:</label>
          <input type="file" name="image[]"/><br/>
          <label for="image">Upload image:</label>
          <input type="file" name="image[]"/><br/>
          <label for="image">Upload image:</label>
          <input type="file" name="image[]"/><br/>
          <label for="image">Upload image:</label>
          <input type="file" name="image[]"/><br/>
          <label for="image">Upload image:</label>
          <input type="file" name="image[]"/><br/>
      </td>
    <?php 
//if the form has been submitted, display result
if (isset($result)) {
echo '<ol>';
foreach ($result as $item) {
	echo "<strong><li>$item</li></strong>";
}
echo '<ol>';
echo 'Please view your listing in the area inserted';
}
?>
    </tr>
  </table>
  <img src="upload/<?php echo $row_listProp['image']; ?>" alt="" />
  <table>
    <tr valign="baseline"> </tr>
    <tr valign="baseline">
      <td align="right"> </td>
      <td> <input type="submit" value="upload" name="upload" id="upload" /></td>
    </tr>
  </table>
  <input type="hidden" name="MM_insert" value="form1" />
</form>
<p> </p>
</body>
</html>
<?php
mysql_free_result($propType);

mysql_free_result($getProp);

mysql_free_result($listProp);
?>

 

Thanks

Donovan

Link to comment
Share on other sites

Im not really sure which is the right code for this as Im still fairly new to php, but the problem that Im having is that when I test my work eg: I want to upload 12 images to a folder and reference them in the database under a column called "images". When I do the upload part and press "submit", the database reflects 12 new entries instead of just one with 12 image references

Link to comment
Share on other sites

Yes we got what you want to do.  Is this your code?  How is it that you can't understand what you've written?

 

Here's where probably you have an issue -- up at the top you do this foreach loop on each file.  It's difficult to tell because the indentation of the code blocks is all over the place and basically a mess, but probably your Insert query is inside this foreach loop, so you are doing the insert for each picture.

 

    foreach ($_FILES['image']['name'] as $number => $file) {

 

Figure out what loops and blocks are appropriate.

Link to comment
Share on other sites

I apologise for it being a bit messy. I have been following several books and have tried to join the code where I thought it would be appropriate.

It doesnt seem that the foreach loop in question is the problem. Correct me if Im wrong, but should I not run an array once the upload is complete. If that is the case, Im still unsure as to how and where I would implement this.

I have amended the code as best as possible. Please can someone have another look.

 

if ((isset($_POST["MM_insert"])) && ($_POST["MM_insert"] == "form1")) {
// define a constant for the maximum upload size 
define ('MAX_FILE_SIZE', 58000);
// define constant for upload folder
define ('UPLOAD_DIR', 'upload/');
    //convert the maximum size to KB
$max = number_format(MAX_FILE_SIZE/1024, 1).'KB';
// create an array of permitted MIME types
$permitted = array('image/gif','image/jpeg','image/pjpeg','image/png');
foreach ($_FILES['image']['name'] as $number => $file) {
	// replace any spaces in orginal filename with undercores
	$file = str_replace(' ','_', $file);
	// begin by assuming the file is unacceptable 
	$sizeOK = false;
	$typeOK = false;
	//check that the file is within the permitted size 
	if ($_FILES['image']['size'][$number] > 0 || $_FILES['image']['size'][$number] <= MAX_FILE_SIZE) {
		$sizeOK = true;
	}
	//check that file is of a permitted MIME type
	foreach ($permitted as $type) {
		if ($type == $_FILES['image']['type'][$number]) {
			$typeOK = true;
			break;
		}
	}
	if ($sizeOK && $typeOK) {
		switch($_FILES['image']['error'][$number]) {
			case 0:
			// make sure file of same name does not already exist
			if (!file_exists(UPLOAD_DIR.$file)) {
				// move the file to the upload folder and rename it
				$success = move_uploaded_file($_FILES['image']['tmp_name'][$number], 
				UPLOAD_DIR.time().$file); 
			}
			else {
				// get the date and time
				ini_set('date.timezone','Europe/London');
				$now = date('Y-m-d-His');
				$success = move_uploaded_file($_FILES['image']['tmp_name'][$number], UPLOAD_DIR.$now.$file);
			}
			if ($success) {
				$result[] = "$file was successfully uploaded";
			}
			else {
				$result[] = "Error uploading $file. Please try again.";
			}
			break;
			case 3:
			$result[] = "Error uploading $file. Please try again.";
			default:
			$result[] = "";
			}
		}
		elseif ($_FILES['image']['error'][$number] == 4) {
			$result[] = 'No file was selected';
		}
		else {
			$result[] = "$file cannot be uploaded because the image size is too large. The Maximum size is $max.  Please re-size and try again.  Or you have an incorrect file type. Acceptable file types are gif, jpg, png.";
		}
	}

$insertSQL = sprintf("INSERT INTO sothebys (address, areas, bedrooms, bathrooms, garages, pool, security, property_type, facing, storey, waterfront, sole_mandate, floor_area, carport, levies_rates, garden, pets_allowed, recreational, prop_desc, price, image) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)",
                       GetSQLValueString($_POST['address'], "text"),
                       GetSQLValueString($_POST['areas'], "text"),
                       GetSQLValueString($_POST['bedrooms'], "int"),
                       GetSQLValueString($_POST['bathrooms'], "int"),
                       GetSQLValueString($_POST['garages'], "text"),
                       GetSQLValueString($_POST['pool'], "text"),
                       GetSQLValueString($_POST['security'], "text"),
                       GetSQLValueString($_POST['property_type'], "text"),
                       GetSQLValueString($_POST['facing'], "text"),
                       GetSQLValueString($_POST['storey'], "text"),
                       GetSQLValueString($_POST['waterfront'], "text"),
                       GetSQLValueString($_POST['sole_mandate'], "text"),
                       GetSQLValueString($_POST['floor_area'], "text"),
                       GetSQLValueString($_POST['carport'], "text"),
                       GetSQLValueString($_POST['levies_rates'], "text"),
                       GetSQLValueString($_POST['garden'], "text"),
                       GetSQLValueString($_POST['pets_allowed'], "text"),
                       GetSQLValueString($_POST['recreational'], "text"),
                       GetSQLValueString($_POST['prop_desc'], "text"),
                       GetSQLValueString($_POST['price'], "int"),
                       GetSQLValueString($file, "text"));

  	mysql_select_db($database_propList, $propList);
  	$Result1 = mysql_query($insertSQL, $propList) or die(mysql_error());
}

Link to comment
Share on other sites

Well, I guess it's magic --- OR you could look carefully at your code, consider what I said, realize that you have the insert query INSIDE the foreach block, and that is the reason you do the query for every image that is uploaded.  Move it outside the block and you will find it is only done once.  OR not.

Link to comment
Share on other sites

I appreciate the assistance.

What I dont appreciate, is your undermining attitude. It seems that you get good at what you do and then everyone that is just getting started is below you and your standards.

I moved the code around, but still cannot seem to get it right.

But dont worry about a response though because I be will looking elsewhere.

Link to comment
Share on other sites

I appreciate the assistance.

What I dont appreciate, is your undermining attitude. It seems that you get good at what you do and then everyone that is just getting started is below you and your standards.

I moved the code around, but still cannot seem to get it right.

But dont worry about a response though because I be will looking elsewhere.

 

Let me straighten you out Don.  I have posted over 3 thousand helpful posts in this forum over a period of years.  I also wrote some tutorials here that were read over 30k times.  On top of that, even though I am a pro LAMP developer, on top of everything else, I have donated several hundred dollars to the forum to help keep it running. 

 

You on the other hand, are new, basically clueless, have contributed nothing to the forum other than a handful of questions, AND CLEARLY HAVEN'T READ THE RULES OF THE FORUM.

 

Notice my emphasis.  See when you come to a community, and that community has rules, it's considered common courtesy to spend a little time reading the rules of the community, which you obviously didn't bother to do. 

 

Despite this fact, I took your gigantic blob of unformatted code, formatted it so I could see where the loops were, and figured out your problem. I told you what that problem was.  Instead of acting upon the information you were given, your reply was

 

It doesnt seem that the foreach loop in question is the problem

 

So apparently you don't require the help of experts like myself -- you know better what your problems are than we do.  If that's the case, by all means, please leave the forum POST HASTE and go somewhere else.  If you'd like I can disable your account for you, to help you on your way. 

 

 

 

 

 

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.