Jump to content

assigning a file directory from dropdown to image upload


davids_media

Recommended Posts

I have this code where I add records:

 

<?php

ini_set('display_errors',1);
error_reporting(-1);

require_once ('./includes/config.inc.php');

require_once (MYSQL);

$add_cat_errors = array();

if ($_SERVER['REQUEST_METHOD'] == 'POST')
{
// Check for a name:
if (empty($_POST['product'])) {
	$add_cat_errors['product'] = 'Please enter the name!';
}

// Check for a description:
if (empty($_POST['prod_descr'])) {
	$add_cat_errors['prod_descr'] = 'Please enter the description!';
}

// Check for a category:
if (!isset($_POST['cat']) || !filter_var($_POST['cat'], FILTER_VALIDATE_INT, array('min_range' => 1))) {
	$add_cat_errors['cat'] = 'Please select a category!';
}

// Check for a price:
if (empty($_POST['price']) || !filter_var($_POST['price'], FILTER_VALIDATE_FLOAT) || ($_POST['price'] <= 0)) {
	$add_cat_errors['price'] = 'Please enter a valid price!';
}

// Check for a category:
if (!isset($_POST['directory']) || !filter_var($_POST['directory'], FILTER_VALIDATE_INT, array('min_range' => 1))) {
	$add_cat_errors['directory'] = 'Please select a directory!';
}

// Check for an image:
if (is_uploaded_file ($_FILES['image']['tmp_name']) && ($_FILES['image']['error'] == UPLOAD_ERR_OK)) {

	$file = $_FILES['image'];

	$size = ROUND($file['size']/1024);

	// Validate the file size:
	if ($size > 512) {
		$add_cat_errors['image'] = 'The uploaded file was too large.';
	} 

	// Validate the file type:
	$allowed_mime = array ('image/jpeg', 'image/JPG', 'image/jpg');
	$allowed_extensions = array ('.jpg', 'jpeg');
	$image_info = getimagesize($file['tmp_name']);
	$ext = substr($file['name'], -4);
	if ( (!in_array($file['type'], $allowed_mime)) 
	||   (!in_array($image_info['mime'], $allowed_mime) ) 
	||   (!in_array($ext, $allowed_extensions) ) 
	) {
		$add_cat_errors['image'] = 'The uploaded file was not of the proper type.';
	} 

	// Move the file over, if no problems:
	if (!array_key_exists('image', $add_cat_errors)) {

		// Create a new name for the file:
		$new_name = (string) sha1($file['name'] . uniqid('',true));

		// Add the extension:
		$new_name .= ((substr($ext, 0, 1) != '.') ? ".{$ext}" : $ext);
		//$new_name = $dir . '/' . $new_name;
		$dest =  "../db/images/$new_name";

		// Move the file to its proper folder but add _tmp, just in case:

		//$dest =  "../db/images/$new_name";
		$dirs = array('full_heads', 'human_hair', 'lip_tattoos', 'ponytails', 'synthetic_hair');

		if (move_uploaded_file($file['tmp_name'], $dest)) {

			// Store the data in the session for later use:
			$_SESSION['image']['new_name'] = $new_name;
			$_SESSION['image']['file_name'] = $file['name'];

			// Print a message:
			echo '<h4>The file has been uploaded!</h4>';

		} else {
			trigger_error('The file could not be moved.');
			unlink ($file['tmp_name']);				
		}

	} // End of array_key_exists() IF.

} elseif (!isset($_SESSION['image'])) { // No current or previous uploaded file.
	switch ($_FILES['image']['error']) {
		case 1:
		case 2:
			$add_cat_errors['image'] = 'The uploaded file was too large.';
			break;
		case 3:
			$add_cat_errors['image'] = 'The file was only partially uploaded.';
			break;
		case 6:
		case 7:
		case 8:
			$add_cat_errors['image'] = 'The file could not be uploaded due to a system error.';
			break;
		case 4:
		default: 
			$add_cat_errors['image'] = 'No file was uploaded.';
			break;
	} // End of SWITCH.

} // End of $_FILES IF-ELSEIF-ELSE.



// Check for a stock:
if (empty($_POST['stock']) || !filter_var($_POST['stock'], FILTER_VALIDATE_INT, array('min_range' => 1))) {
	$add_cat_errors['stock'] = 'Please enter the quantity in stock!';
}

if (empty($add_cat_errors))
{
$query = "INSERT INTO product (product, prod_descr, catID, price, dirID, image, stock) VALUES (?, ?, ?, ?, ?, ?, ?)";
	// Prepare the statement:
$stmt = mysqli_prepare($dbc, $query);
// For debugging purposes:
	// if (!$stmt) echo mysqli_stmt_error($stmt);

	// Bind the variables:
mysqli_stmt_bind_param($stmt, 'ssssssi', $name, $desc, $_POST['cat'], $_POST['price'], $_POST['directory'], $_SESSION['image']['new_name'], $_POST['stock']);

	// Make the extra variable associations:
	$name = strip_tags($_POST['product']);
	$desc = strip_tags($_POST['prod_descr']);
	// Execute the query:
	mysqli_stmt_execute($stmt);

	if (mysqli_stmt_affected_rows($stmt) == 1) { // If it ran OK.

		// Print a message:
		echo '<h4>The product has been added!</h4>';

		// Clear $_POST:
		$_POST = array();

		// Clear $_FILES:
		$_FILES = array();

		// Clear $file and $_SESSION['image']:
		unset($file, $_SESSION['image']);

	} else { // If it did not run OK.
		trigger_error('The product could not be added due to a system error. We apologize for any inconvenience.');
		unlink ($dest);
	}

} // End of $errors IF.

} else { // Clear out the session on a GET request:
unset($_SESSION['image']);	
} // End of the submission IF.

require_once ('./includes/form_functions.inc.php');
?>

<form enctype="multipart/form-data" action="add_product.php" method="post" accept-charset="utf-8">

<input type="hidden" name="MAX_FILE_SIZE" value="524288" />

		Product<br /><?php create_form_input('product', 'text', $add_cat_errors); ?>
            
            Description<br /><?php create_form_input('prod_descr', 'textarea', $add_cat_errors); ?>
            
Category<br /><select name="cat"<?php if (array_key_exists('cat', $add_cat_errors)); ?>>
		<option>Select One</option>
		<?php // Retrieve all the categories and add to the pull-down menu:
		$q = 'SELECT catID, cat FROM category ORDER BY cat ASC';		
		$r = mysqli_query ($dbc, $q);
			while ($row = mysqli_fetch_array ($r, MYSQLI_NUM)) {
				echo "<option value=\"$row[0]\"";
				// Check for stickyness:
				if (isset($_POST['cat']) && ($_POST['cat'] == $row[0]) ) echo ' selected="selected"';
				echo ">$row[1]</option>\n";
			}
		?>
		</select><?php if (array_key_exists('cat', $add_cat_errors)) echo $add_cat_errors['cat']; ?>
            
            Price<br /><?php create_form_input('price', 'text', $add_cat_errors); ?>
            
            Directory<br /><select name="directory"<?php if (array_key_exists('directory', $add_cat_errors)); ?>>
		<option>Select One</option>
		<?php // Retrieve all the categories and add to the pull-down menu:
		$q = 'SELECT dirID, directory FROM directory ORDER BY directory ASC';		
		$r = mysqli_query ($dbc, $q);
			while ($row = mysqli_fetch_array ($r, MYSQLI_NUM)) {
				echo "<option value=\"$row[0]\"";
				// Check for stickyness:
				if (isset($_POST['directory']) && ($_POST['directory'] == $row[0]) ) echo ' selected="selected"';
				echo ">$row[1]</option>\n";
			}
		?>
		</select><?php if (array_key_exists('directory', $add_cat_errors)) echo $add_cat_errors['directory']; ?>
</select>
            
            			Image<br /><?php

		// Check for an error:
		if (array_key_exists('image', $add_cat_errors)) {

			echo $add_cat_errors['image'] . '<br /><input type="file" name="image"/>';

		} else { // No error.

			echo '<input type="file" name="image" />';

			// If the file exists (from a previous form submission but there were other errors),
			// store the file info in a session and note its existence:		
			if (isset($_SESSION['image'])) {
				echo "<br />Currently '{$_SESSION['image']['file_name']}'";
			}

		} // end of errors IF-ELSE.
	 ?>
         				<br />

		Stock<br /><?php create_form_input('stock', 'text', $add_cat_errors); ?>


<input type="submit" value="Add This Product" class="button" />


</fieldset>

</form> 

 

What I want to achieve is this;

 

When a record is being inserted, a user will make a selection from the dropdown box with a list of directories. Then, a user will upload an image. When a image is uploaded and a directory is chosen, I want the image to be assigned to a specific directory from the list so when the record is inserted, that image will be placed in the specific directory. How do I achieve this please?

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.