Jump to content

Upload Image and Insert Filename (including folder image is stored in) into DB


RyanMinor

Recommended Posts

Hi everyone, this is my first post here. What I am trying to do is to have a form on my administrator section that allows me to upload an image and automatically insert the foldername and image name into my MySQL database. I can get the image name to store in my DB (imagename.jpg), but I also need the folder name to be inserted as well (images/imagename.jpg). Below is my code. Thanks in advance!

 

<?php require_once('Connections/connect.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;
}
}

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

if ((isset($_POST["MM_insert"])) && ($_POST["MM_insert"] == "uploadImage")) {
}

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

if (array_key_exists('upload', $_POST)) {

  $insertSQL = sprintf("INSERT INTO workout (Name, Image) VALUES (%s, %s)",
                       GetSQLValueString($_POST['Workout_Name'], "text"),
                       GetSQLValueString($_FILES['image']['name'], "text"));

  mysql_select_db($database_connect, $connect);
  $Result1 = mysql_query($insertSQL, $connect) or die(mysql_error());

// define constant for upload folder
define('UPLOAD_DIR', 'C:/wamp/www/theworkoutstore/images/');
// move the file to the upload folder and rename it
// 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 a permitted MIME type
foreach ($permitted as $type) {
if ($type == $_FILES['image']['type']) {
$typeOK = true;
break;
}
}

if ($sizeOK && $typeOK) {
switch($_FILES['image']['error']) {
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'], UPLOAD_DIR.$file);
}
else {
// get the date and time
ini_set('date.timezone', 'America/Virginia');
$now = date('Y-m-d-His');
$success = move_uploaded_file($_FILES['image']['tmp_name'], UPLOAD_DIR.$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>Administrator Section - Insert</title>
<style type="text/css">
<!--
body,td,th {
font-family: Calibri;
font-size: 11pt;
color: #000000;
}
.style1 {
color: #FFFFFF;
font-weight: bold;
font-size: 16pt;
}
.style2 {color: #FFFFFF}
-->
</style></head>

<body>
<table width="800" border="0" align="center" cellpadding="0" cellspacing="0">
  <tr>
    <td width="800"><img src="images/banner.png" width="1000" height="200" /></td>
  </tr>
  <tr>
    <td bgcolor="#000033"><div align="center"><span class="style1">ADMINISTRATOR SECTION</span></div></td>
  </tr>
  <tr>
    <td><table width="100%" border="0" align="center" cellpadding="0" cellspacing="0">
        <tr>
          <td width="20%" valign="top" bgcolor="#000033"> </td>
          <td width="80%" valign="top"><br />
            <table width="60%" border="1" align="center" cellpadding="5" cellspacing="0" bordercolor="#000000">
              <tr>
                <td bgcolor="#CCCCCC">
                <?php
                // if the form has been submitted, display result
                if (isset($result)) {
                  echo "<p><strong>$result</strong></p>";
                  }
                ?>
                <form action="<?php echo $editFormAction; ?>" method="POST" enctype="multipart/form-data" name="uploadImage" id="uploadImage">
                  <p>
                    <label for="Workout_Name">Workout Name:</label>
                    <input type="text" name="Workout_Name" id="Workout_Name" />
                    <label for="image"><br />
                    <br />
                    Upload Image:</label>
                    <input type="hidden" name="MAX_FILE_SIZE" value="<?php echo MAX_FILE_SIZE; ?>" />
                    <input type="file" name="image" id="image" />
                  </p>
                  <p align="center">
                    <input type="submit" name="upload" id="upload" value="Upload" />
                  </p>
                  <input type="hidden" name="MM_insert" value="uploadImage" />
                </form>
                </td>
              </tr>
            </table>
          <br /></td>
        </tr>
      </table>
    </td>
  </tr>
</table>
</body>
</html>

Just replace this query

$insertSQL = sprintf("INSERT INTO workout (Name, Image) VALUES (%s, %s)",
                       GetSQLValueString($_POST['Workout_Name'], "text"),
                       'images/'.GetSQLValueString($_FILES['image']['name'], "text"));

Nevermind, I got it to work. Here is the fixed version if anyone else was wondering as well:

 

  $insertSQL = sprintf("INSERT INTO workout (Name, Type, Hyperlink, `Description`, Image, Profit) VALUES (%s, %s, %s, %s, %s, %s)",
                       GetSQLValueString($_POST['Name'], "text"),
                       GetSQLValueString($_POST['Type'], "text"),
                       GetSQLValueString($_POST['Hyperlink'], "text"),
                       GetSQLValueString($_POST['Description'], "text"),
                       GetSQLValueString("images/".$_FILES['image']['name'], "text"),
                       GetSQLValueString($_POST['Profit'], "double"));

 

Thanks for the help.

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.