Jump to content

Upload File & Record


toad78

Recommended Posts

I have an insert form that I want to give the client an option to upload an image or to select an image. If the client want to upload an image, I'd like the image filename to list in the dbase (which it doesn't) and the file to go a specific directory; if the client chooses an item in the select list, it would record in the dbase record (which it does).

 

Can someone give me a hand?

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;
}
}

$editFormAction = $_SERVER['PHP_SELF'];
if (isset($_SERVER['QUERY_STRING'])) {
  $editFormAction .= "?" . htmlentities($_SERVER['QUERY_STRING']);
}

if ((isset($_POST["MM_insert"])) && ($_POST["MM_insert"] == "form1")) {
  $insertSQL = sprintf("INSERT INTO class_programs (classpro_img, classpro_classname, classpro_classlevel, classpro_tuition, classpro_detail, classpro_Mon, classpro_Tue, classpro_Wed, classpro_Thur, classpro_Fri, classpro_Sat, classpro_age) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)",
                       GetSQLValueString($_FILES['classpro_img'], "text"),
                       GetSQLValueString($_POST['classpro_classname'], "text"),
                       GetSQLValueString($_POST['classpro_classlevel'], "text"),
                       GetSQLValueString($_POST['classpro_tuition'], "text"),
                       GetSQLValueString($_POST['classpro_detail'], "text"),
                       GetSQLValueString($_POST['classpro_Mon'], "text"),
                       GetSQLValueString($_POST['classpro_Tue'], "text"),
                       GetSQLValueString($_POST['classpro_Wed'], "text"),
                       GetSQLValueString($_POST['classpro_Thur'], "text"),
                       GetSQLValueString($_POST['classpro_Fri'], "text"),
                       GetSQLValueString($_POST['classpro_Sat'], "text"),
                       GetSQLValueString($_POST['classpro_age'], "text"));

  mysql_select_db($database_wvgsadmin, $wvgsadmin);
  $Result1 = mysql_query($insertSQL, $wvgsadmin) or die(mysql_error());

  $insertGoTo = "class_list.php";
  if (isset($_SERVER['QUERY_STRING'])) {
    $insertGoTo .= (strpos($insertGoTo, '?')) ? "&" : "?";
    $insertGoTo .= $_SERVER['QUERY_STRING'];
  }
  header(sprintf("Location: %s", $insertGoTo));
}

// define a constant for the maximum upload size
define ('MAX_FILE_SIZE', 51200);

if (array_key_exists('insert', $_POST)) {
  // define constant for upload folder
  define('UPLOAD_DIR', '/localhost/wvgymnastics/photos/');
  // replace any spaces in original filename with underscores
  // at the same time, assign to a simpler variable
  $file = str_replace(' ', '_', $_FILES['image']['name']);
  // 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');
  // begin by assuming the file is unacceptable
  $sizeOK = false;
  $typeOK = false;
  
  // check that file is within the permitted size
  if ($_FILES['image']['size'] > 0 && $_FILES['image']['size'] <= MAX_FILE_SIZE) {
    $sizeOK = true;
}

  // check that file is of an permitted MIME type
  foreach ($permitted as $type) {
    if ($type == $_FILES['image']['type']) {
      $typeOK = true;
  break;
  }
}
  
  if ($sizeOK && $typeOK) {
    switch($_FILES['image']['error']) {
  case 0:
	// $username would normally come from a session variable
        $username = '';
	// if the user's subfolder doesn't exist yet, create it
	if (!is_dir(UPLOAD_DIR.$username)) {
	  mkdir(UPLOAD_DIR.$username);
	  }
        // check if a file of the same name has been uploaded
	if (!file_exists(UPLOAD_DIR.$username.'/'.$file)) {
	  // move the file to the upload folder and rename it
	  $success = move_uploaded_file($_FILES['image']['tmp_name'], UPLOAD_DIR.$username.'/'.$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'], UPLOAD_DIR.$username.'/'.$now.$file);
	  }
	if ($success) {
          $result = "$file uploaded successfully";
      }
	else {
	  $result = "Error uploading $file. Please try again.";
	  }
    break;
  case 3:
	$result = "Error uploading $file. Please try again.";
  default:
        $result = "System error uploading $file. Contact webmaster.";
  }
    }
  elseif ($_FILES['image']['error'] == 4) {
    $result = 'No file selected';
}
  else {
    $result = "$file cannot be uploaded. Maximum size: $max. Acceptable file types: gif, jpg, png.";
}
  }
?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>WVGS - Insert Class Schedule</title>
<link href="../../styles/admin.css" rel="stylesheet" type="text/css" media="screen" />
<link rel="shortcut icon" href="../../favicon.ico" type="image/x-icon" /> 
<link rel="icon" href="../../favicon.ico" type="image/x-icon" />
<style type="text/css">
<!--
.small {font-size: x-small;}
-->
</style>
</head>

<body>
<div class="wrap"><h1>Insert Class Schedule</h1>
<form method="post" name="form1" enctype="multipart/form-data" action="<?php echo $editFormAction; ?>">
<table align="center" cellspacing="3">
<tr valign="baseline">
<td nowrap align="right"><label for="image">Upload image:</label></td>
<td><input type="hidden" name="MAX_FILE_SIZE" value="<?php echo MAX_FILE_SIZE; ?>" /><input type="file" name="image" id="image" /></td>
</tr>
<tr valign="baseline">
<td nowrap align="right">Image:</td>
<td><select name="classpro_img">
<option value="" >No image</option>
<?php buildImageList('../../photos/'); ?>
</select></td>
</tr>
<tr valign="baseline">
<td nowrap align="right">Class Name:</td>
<td><input name="classpro_classname" type="text" class="widebox" value="" size="255"></td>
</tr>
<tr valign="baseline">
<td nowrap align="right">Class Level:</td>
<td><input type="text" name="classpro_classlevel" value="" size="32"> 
<span class="small">(Preschool, Recreational, Developmental, Team) </span></td>
</tr>
<tr valign="baseline">
<td nowrap align="right">Ages:</td>
<td><input type="text" name="classpro_age" value="" size="10"> 
<span class="small"> 3 - 4 (there is a space between the numbers and dash) </span></td>
</tr>
<tr valign="baseline">
<td nowrap align="right">Tuition:<br /></td>
<td><input type="text" name="classpro_tuition" value="" size="10">
<span class="small">(include decimal, 
exclude dollar ($) sign)</span></td>
</tr>
<tr valign="baseline">
<td nowrap align="right" valign="top">Description:<br />
<span class="small">(use Return/Enter key<br />
to create a new line)</span><br /></td>
<td><textarea name="classpro_detail" cols="50" rows="5"></textarea></td>
</tr>
<tr valign="baseline">
<td colspan="3" nowrap> </td>
</tr>
<tr valign="baseline">
<td colspan="3" nowrap><span class="small">(use Return/Enter key to create a new line when entering the times of day;<br />
format 00:00 - 00:00 (there is a space between the time and dash))</span></td>
</tr>
<tr valign="baseline">
<td nowrap align="right">Mon:</td>
<td><textarea name="classpro_Mon" cols="15" rows="5"></textarea></td>
</tr>
<tr valign="baseline">
<td nowrap align="right">Tue:</td>
<td><textarea name="classpro_Tue" cols="15" rows="5"></textarea></td>
</tr>
<tr valign="baseline">
<td nowrap align="right">Wed:</td>
<td><textarea name="classpro_Wed" cols="15" rows="5"></textarea></td>
</tr>
<tr valign="baseline">
<td nowrap align="right">Thur:</td>
<td><textarea name="classpro_Thur" cols="15" rows="5"></textarea></td>
</tr>
<tr valign="baseline">
<td nowrap align="right">Fri:</td>
<td><textarea name="classpro_Fri" cols="15" rows="5"></textarea></td>
</tr>
<tr valign="baseline">
<td nowrap align="right">Sat:</td>
<td><textarea name="classpro_Sat" cols="15"></textarea></td>
</tr>
<tr valign="baseline">
<td nowrap align="right"> </td>
<td><input name="insert" type="submit" id="insert" value="Insert record"></td>
</tr>
</table>
<input type="hidden" name="MM_insert" value="form1">
</form>
<p style="text-align: right; font-weight: bold;"><a href="../menu.php">Admin menu</a>      <a href="class_list.php">Class List</a>      Log Out</p></div>
</body>
</html>

<?php
function buildImageList($imageFolder, $recordset=NULL) {
// Check whether image folder has trailing slash, add if needed
$imageFolder = strrpos($imageFolder,'/') == strlen($imageFolder-1) ? $imageFolder : "$imageFolder/";
// Execute code if images folder can be opened, or fail silently
if ($theFolder = @opendir($imageFolder)) {
  // Create an array of image types
  $imageTypes = array('jpg','jpeg','gif','png');
  // Traverse images folder, and add filename to $img array if an image
  while (($imageFile = readdir($theFolder)) !== false) {
    $fileInfo = pathinfo($imageFile);
    if (in_array($fileInfo['extension'],$imageTypes)) {
      $img[] = $imageFile;
      }
    }
  // Close the stream from the images folder
  closedir($theFolder);
  // Check the $img array is not empty
  if ($img) {
    // Sort in natural, case-insensitive order, and populate menu
    natcasesort($img);
    foreach ($img as $image) {
      echo "<option value='$image'";
  // Set selected image if recordset details supplied
  if ($recordset != NULL && $recordset == $image) {
    echo  ' selected="selected"';
	}
  echo ">$image</option>\n";
      }
    }
  }
}
?>

 

I thank you for your time!

 

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.