• Global community
    • Language:
      • Deutsch
      • English
      • Español
      • Français
      • Português
  • 日本語コミュニティ
    Dedicated community for Japanese speakers
  • 한국 커뮤니티
    Dedicated community for Korean speakers
Exit
0

how create a path for images to database

New Here ,
Sep 06, 2015 Sep 06, 2015

Copy link to clipboard

Copied

Hi

I've created upload files I just need to link it to the database in dreamweaver cs6. The file go into a folder on the server I just need to know how to link the image file to the database when submit.

many thanks

Richard

Views

751

Translate

Translate

Report

Report
Community guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
community guidelines
Community Expert ,
Sep 06, 2015 Sep 06, 2015

Copy link to clipboard

Copied

Please post your PHP for the file upload script.

Nancy O.

Nancy O'Shea— Product User, Community Expert & Moderator

Votes

Translate

Translate

Report

Report
Community guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
community guidelines
New Here ,
Sep 06, 2015 Sep 06, 2015

Copy link to clipboard

Copied

Hi here is the php code

<?php require_once('../Connections/myconnect.php'); ?>

<?php
if (!function_exists("GetSQLValueString")) {
function GetSQLValueString($theValue, $theType, $theDefinedValue = "", $theNotDefinedValue = "")
{
  if (PHP_VERSION < 6) {
    $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"] == "productForm")) {
  $insertSQL = sprintf("INSERT INTO cars (productName, make, model, colour, `year`, engineSize, fuelType, gearBox, details) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s)",
                       GetSQLValueString($_POST['productName'], "text"),
                       GetSQLValueString($_POST['make'], "text"),
                       GetSQLValueString($_POST['model'], "text"),
                       GetSQLValueString($_POST['colour'], "text"),
                       GetSQLValueString($_POST['year'], "text"),
                       GetSQLValueString($_POST['engineSize'], "text"),
                       GetSQLValueString($_POST['fuelType'], "text"),
                       GetSQLValueString($_POST['gearBox'], "text"),
                       GetSQLValueString($_POST['details'], "text"));

  mysql_select_db($database_myconnect, $myconnect);
  $Result1 = mysql_query($insertSQL, $myconnect) or die(mysql_error());

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

mysql_select_db($database_myconnect, $myconnect);
$query_product = "SELECT * FROM cars";
$product = mysql_query($query_product, $myconnect) or die(mysql_error());
$row_product = mysql_fetch_assoc($product);
$totalRows_product = mysql_num_rows($product);

$query_ManageUsers = "SELECT * FROM users WHERE userLevel = 0 ORDER BY RegDate ASC";
$ManageUsers = mysql_query($query_ManageUsers, $myconnect) or die(mysql_error());
$row_ManageUsers = mysql_fetch_assoc($ManageUsers);
$totalRows_ManageUsers = mysql_num_rows($ManageUsers);
$query_ManageUsers = "SELECT * FROM users WHERE userLevel = 0 ORDER BY RegDate ASC";
$ManageUsers = mysql_query($query_ManageUsers, $myconnect) or die(mysql_error());
$row_ManageUsers = mysql_fetch_assoc($ManageUsers);
$totalRows_ManageUsers = mysql_num_rows($ManageUsers);
$query_ManageUsers = "SELECT * FROM users WHERE userLevel = 0 ORDER BY RegDate ASC";
$ManageUsers = mysql_query($query_ManageUsers, $myconnect) or die(mysql_error());
$row_ManageUsers = mysql_fetch_assoc($ManageUsers);
$totalRows_ManageUsers = mysql_num_rows($ManageUsers);
$query_ManageUsers = "SELECT * FROM users WHERE userLevel = 1 ORDER BY RegDate ASC";
$ManageUsers = mysql_query($query_ManageUsers, $myconnect) or die(mysql_error());
$row_ManageUsers = mysql_fetch_assoc($ManageUsers);
$totalRows_ManageUsers = mysql_num_rows($ManageUsers);
?>

<?php
use foundationphp\UploadFile;

$max = 20000 * 1024;
$result = array();
if (isset($_POST['upload'])) {
require_once '../src/foundationphp/UploadFile.php';
$destination = __DIR__ . '/inventory_images/';
    try {
     $upload = new UploadFile($destination);
     //$upload->setMaxSize($max);
     $upload->allowAllTypes();
     $upload->upload();
     $result = $upload->getMessages();
    } catch (Exception $e) {
     $result[] = $e->getMessage();
    }
}
?>

<!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>Untitled Document</title>
<link href="../images/css/layout.css" rel="stylesheet" type="text/css" />
<link href="../images/css/style.css" rel="stylesheet" type="text/css" />
<link href="../images/css/links.css" rel="stylesheet" type="text/css" />
<link href="../SpryAssets/SpryValidationTextField.css" rel="stylesheet" type="text/css" />
<link href="../SpryAssets/SpryValidationTextarea.css" rel="stylesheet" type="text/css" />
<script src="../SpryAssets/SpryValidationTextField.js" type="text/javascript"></script>
<script src="../SpryAssets/SpryValidationTextarea.js" type="text/javascript"></script>
</head>

<body>

<form id="productForm" name="productForm" method="POST" action="<?php echo $editFormAction; ?>" enctype="multipart/form-data">
          <table width="630" border="0" cellspacing="2">
            <tr>
              <td width="143" align="right">Product Name:</td>
              <td width="477"><span id="sprytextfield2">
              <label for="productName"></label>
              <input name="productName" type="text" id="productName" size="60" maxlength="255" />
              <span class="textfieldRequiredMsg">A value is required.</span><span class="textfieldMinCharsMsg">Minimum number of characters not met.</span><span class="textfieldMaxCharsMsg">Exceeded maximum number of characters.</span></span></td>
            </tr>
            <tr>
              <td align="right">Make:</td>
              <td><span id="sprytextfield3">
                <label for="make"></label>
                <input type="text" name="make" id="make" />
                <span class="textfieldRequiredMsg">A value is required.</span></span></td>
            </tr>
            <tr>
              <td align="right">Model:</td>
              <td><span id="sprytextfield4">
                <label for="model"></label>
                <input type="text" name="model" id="model" />
                <span class="textfieldRequiredMsg">A value is required.</span></span></td>
            </tr>
            <tr>
              <td align="right">Colour:</td>
              <td><span id="sprytextfield5">
                <label for="colour"></label>
                <input type="text" name="colour" id="colour" />
                <span class="textfieldRequiredMsg">A value is required.</span></span></td>
            </tr>
            <tr>
              <td align="right">Year/Reg:</td>
              <td><span id="sprytextfield6">
                <label for="year"></label>
                <input type="text" name="year" id="year" />
                <span class="textfieldRequiredMsg">A value is required.</span></span></td>
            </tr>
            <tr>
              <td align="right">Engine Size:</td>
              <td><span id="sprytextfield7">
                <label for="engineSize"></label>
                <input type="text" name="engineSize" id="engineSize" />
                <span class="textfieldRequiredMsg">A value is required.</span></span></td>
            </tr>
            <tr>
              <td align="right">Fuel Type:</td>
              <td><span id="sprytextfield8">
                <label for="fuelType"></label>
                <input type="text" name="fuelType" id="fuelType" />
                <span class="textfieldRequiredMsg">A value is required.</span></span></td>
            </tr>
            <tr>
              <td align="right">Gear Box:</td>
              <td><span id="sprytextfield9">
                <label for="gearBox"></label>
                <input type="text" name="gearBox" id="gearBox" />
                <span class="textfieldRequiredMsg">A value is required.</span></span></td>
            </tr>
            <tr>
              <td align="right">Details:</td>
              <td><span id="sprytextarea1">
                <label for="details"></label>
                <textarea name="details" id="details" cols="60" rows="5"></textarea>
                <span class="textareaRequiredMsg">A value is required.</span></span></td>
            </tr>
            <tr>
              <td align="right">Select file:</td>
              <td><input type="hidden" name="MAX_FILE_SIZE" value="<?php echo $max; ?>">
                <input type="file" name="filename[]" id="filename01"></td>
            </tr>
            <tr>
              <td align="right">Select file:</td>
              <td><input type="hidden" name="MAX_FILE_SIZE" value="<?php echo $max; ?>">
                <input type="file" name="filename[]" id="filename02"></td>
            </tr>
            <tr>
              <td align="right">Select file:</td>
              <td><input type="hidden" name="MAX_FILE_SIZE" value="<?php echo $max; ?>">
                <input type="file" name="filename[]" id="filename03"></td>
            </tr>
            <tr>
              <td align="right">Select file:</td>
              <td><input type="hidden" name="MAX_FILE_SIZE" value="<?php echo $max; ?>">
                <input type="file" name="filename[]" id="filename04"></td>
            </tr>
            <tr>
              <td align="right"> </td>
              <td> </td>
            </tr>
            <tr>
              <td align="right"> </td>
              <td><input type="submit" name="addproduct" id="addproduct" value="Add Product" /></td>
            </tr>
            <tr>
              <td align="right"> </td>
              <td> </td>
            </tr>
          </table>
          <input type="hidden" name="MM_insert" value="productForm" />
        </form>
</body>
</html>

this is the upload.php file

<?php
namespace foundationphp;

class UploadFile
{
protected $destination;
protected $messages = array();
protected $maxSize = 2051200;
protected $permittedTypes = array(
   'image/jpeg',
   'image/pjpeg',
   'image/gif',
   'image/png',
   'image/webp'
);
protected $newName;
protected $typeCheckingOn = true;
protected $notTrusted = array('bin', 'cgi', 'exe', 'js', 'pl', 'php', 'py', 'sh');
protected $suffix = '.upload';
protected $renameDuplicates;

public function __construct($uploadFolder)
{
  if (!is_dir($uploadFolder) || !is_writable($uploadFolder)) {
   throw new \Exception("$uploadFolder must be a valid, writable folder.");
  }
  if ($uploadFolder[strlen($uploadFolder)-1] != '/') {
   $uploadFolder .= '/';
  }
  $this->destination = $uploadFolder;
}

public function setMaxSize($bytes)
{
  $serverMax = self::convertToBytes(ini_get('upload_max_filesize'));
  if ($bytes > $serverMax) {
   throw new \Exception('Maximum size cannot exceed server limit for individual files: ' .
self::convertFromBytes($serverMax));
  }
  if (is_numeric($bytes) && $bytes > 0) {
   $this->maxSize = $bytes;
  }
}

public static function convertToBytes($val)
{
  $val = trim($val);
  $last = strtolower($val[strlen($val)-1]);
  if (in_array($last, array('g', 'm', 'k'))){
   switch ($last) {
    case 'g':
     $val *= 1024;
    case 'm':
     $val *= 1024;
    case 'k':
     $val *= 1024;
   }
  }
  return $val;
}

public static function convertFromBytes($bytes)
{
  $bytes /= 1024;
  if ($bytes > 1024) {
   return number_format($bytes/1024, 1) . ' MB';
  } else {
   return number_format($bytes, 1) . ' KB';
  }
}

public function allowAllTypes($suffix = null)
{
  $this->typeCheckingOn = false;
  if (!is_null($suffix)) {
   if (strpos($suffix, '.') === 0 || $suffix == '') {
    $this->suffix = $suffix;
   } else {
    $this->suffix = ".$suffix";
   }
  }
}

public function upload($renameDuplicates = true)
{
  $this->renameDuplicates = $renameDuplicates;
  $uploaded = current($_FILES);
  if (is_array($uploaded['name'])) {
   foreach ($uploaded['name'] as $key => $value) {
    $currentFile['name'] = $uploaded['name'][$key];
    $currentFile['type'] = $uploaded['type'][$key];
    $currentFile['tmp_name'] = $uploaded['tmp_name'][$key];
    $currentFile['error'] = $uploaded['error'][$key];
    $currentFile['size'] = $uploaded['size'][$key];
    if ($this->checkFile($currentFile)) {
     $this->moveFile($currentFile);
    }
   }
  } else {
   if ($this->checkFile($uploaded)) {
    $this->moveFile($uploaded);
   }
  }
}

public function getMessages()
{
  return $this->messages;
}

protected function checkFile($file)
{
  if ($file['error'] != 0) {
   $this->getErrorMessage($file);
   return false;
  }
  if (!$this->checkSize($file)) {
   return false;
  }
  if ($this->typeCheckingOn) {
      if (!$this->checkType($file)) {
       return false;
   }
  }
  $this->checkName($file);
  return true;
}

protected function getErrorMessage($file)
{
  switch($file['error']) {
   case 1:
   case 2:
    $this->messages[] = $file['name'] . ' is too big: (max: ' .
    self::convertFromBytes($this->maxSize) . ').';
    break;
   case 3:
    $this->messages[] = $file['name'] . ' was only partially uploaded.';
    break;
   case 4:
    $this->messages[] = 'No file submitted.';
    break;
   default:
    $this->messages[] = 'Sorry, there was a problem uploading ' . $file['name'];
    break;
  }
}

protected function checkSize($file)
{
  if ($file['size'] == 0) {
   $this->messages[] = $file['name'] . ' is empty.';
   return false;
  } elseif ($file['size'] > $this->maxSize) {
   $this->messages[] = $file['name'] . ' exceeds the maximum size for a file ('
     . self::convertFromBytes($this->maxSize) . ').';
   return false;
  } else {
   return true;
  }
}

protected function checkType($file)
{
  if (in_array($file['type'], $this->permittedTypes)) {
   return true;
  } else {
   $this->messages[] = $file['name'] . ' is not permitted type of file.';
   return false;
  }
}

protected function checkName($file)
{
  $this->newName = null;
  $nospaces = str_replace(' ', '_', $file['name']);
  if ($nospaces != $file['name']) {
   $this->newName = $nospaces;
  }
  $nameparts = pathinfo($nospaces);
  $extension = isset($nameparts['extension']) ? $nameparts['extension'] : '';
  if (!$this->typeCheckingOn && !empty($this->suffix)) {
   if (in_array($extension, $this->notTrusted) || empty($extension)) {
    $this->newName = $nospaces . $this->suffix;
   }
  }
  if ($this->renameDuplicates) {
   $name = isset($this->newName) ? $this->newName : $file['name'];
   $existing = scandir($this->destination);
   if (in_array($name, $existing)) {
    $i = 1;
    do {
     $this->newName = $nameparts['filename'] . '_' . $i++;
     if (!empty($extension)) {
      $this->newName .= ".$extension";
     }
     if (in_array($extension, $this->notTrusted)) {
      $this->newName .= $this->suffix;
     }
    } while (in_array($this->newName, $existing));
   }
  }
}

protected function moveFile($file)
{
  $filename = isset($this->newName) ? $this->newName : $file['name'];
  $success = move_uploaded_file($file['tmp_name'], $this->destination . $filename);
  if ($success) {
   $result = $file['name'] . ' was uploaded successfully';
   if (!is_null($this->newName)) {
    $result .= ', and was renamed ' . $this->newName;
   }
   $result .= '.';
   $this->messages[] = $result;
  } else {
   $this->messages[] = 'Could not upload ' . $file['name'];
  }
}
}

many thanks

Richard

Votes

Translate

Translate

Report

Report
Community guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
community guidelines
LEGEND ,
Sep 06, 2015 Sep 06, 2015

Copy link to clipboard

Copied

rich1973 wrote:

Hi

I've created upload files I just need to link it to the database in dreamweaver cs6. The file go into a folder on the server I just need to know how to link the image file to the database when submit.

many thanks

Richard

Depends what you are doing and what your workflow is.

If the images are going to be available for one client to insert into their webpages then on the 'insert' page you can list all the images which are in a folder using a <select></select> list, which will be part of a form, like below: (obviously this is php so your pages need the .php extension)

<select name="uploaded_images" id="uploaded_images">

<option value="">Select Image</option>

<?php

$a = array();

$dir = 'uploaded_images';

if ($handle = opendir($dir)) {

  while (false !== ($file = readdir($handle))) {

    if (preg_match("/\.png$/", $file)) $a[] = $file;

    elseif (preg_match("/\.jpg$/", $file)) $a[] = $file;

    elseif (preg_match("/\.jpeg$/", $file)) $a[] = $file;

                elseif (preg_match("/\.gif$/", $file)) $a[] = $file;

  }

  closedir($handle);

}

natsort($a); // sort.

foreach ($a as $i) {

  echo "<option value=".$i.">".$i."</option>";

}

?>

</select>

The above makes all the images in a folder named 'uploaded_images' available for selection to the user. Once the user submits the form the image name gets inserted into a database via a mysli query

Its not visual by any means but is a useful method for a 'template' style page where images are allocated a consistant position on a 'details' page.

If you want something which is more felxible and graphical then you need to use something like KCFinder web file manager - SunHater Projects and integrate that with your Content Management System.

Votes

Translate

Translate

Report

Report
Community guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
community guidelines
Community Expert ,
Sep 06, 2015 Sep 06, 2015

Copy link to clipboard

Copied

What if the file already exists?

Shouldn't there be some provision for handling duplicates?

Nancy O.

Nancy O'Shea— Product User, Community Expert & Moderator

Votes

Translate

Translate

Report

Report
Community guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
community guidelines
LEGEND ,
Sep 06, 2015 Sep 06, 2015

Copy link to clipboard

Copied

Nancy O. wrote:

What if the file already exists?

Shouldn't there be some provision for handling duplicates?

Nancy O.

Sure that all needs to be handled in the 'upload' file or KCFinder will cope with that for you.

As I'm sure you are aware its fairly straight forward to upload a file to a folder but you have to take other things into consideration too like eliminating the space between file names, the size, what formats you allow and how you wish those formats to be written and as you say to check the file name doesnt already exit, it's not all plain sailing as one might imagine.

Votes

Translate

Translate

Report

Report
Community guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
community guidelines
LEGEND ,
Sep 07, 2015 Sep 07, 2015

Copy link to clipboard

Copied

rich1973 ~ In order to keep track of what image belongs to what person, you need to track that information. As with anything in programming, there's usually a few ways to do it.

The code you're using is a big mix of some hand coding as well as generated code, that's easy to see. What's not easy to see is your level of comfort with PHP or databases. Before writing out any of the many ways to solve your issue it'd be useful to know a few things.

- Are you comfortable editing databases?

- If so, does your current 'cars' table in that database contain a unique/primary key column for each row?

- Are you looking more for a database + code fix or more of a code + filesystem fix?

- How many cars do you anticipate this site to grow to, or users? I know we all want the next cars.com, but be honest. Is this a small, medium, or attempting to be a huge site?

The reason we really need these answers is they all cross-relate to each other. There's a lot of problems in that code, like redundantly querying for the users over and over for no reason (you probably copied and pasted the code by accident). Outside that there's security issues regarding allowing any file names including (the_go_f***_yourself_car.jpg) that can cause you headaches later on. Your upload script doesn't even let you specify names, just a destination. It leaves it up to you to adjust the $_FILES array and just uses the given names of the original files. Lots of issues.

So before addressing all the code issues here, please provide those details first.

osgood_ ~ you forgot the trailing /i on the RegExp. Users and filesystems are both more than happy to supply mycar.PNG which would be valid but missed in the script.

Nancy ~ The script actually has a value for handling duplicate filenames auto-defaulting to handle those, but the upload script overall needs some serious work ><. It's good you pointed it out because if there is a duplication, the script will need to report a new name returned in the results.

Votes

Translate

Translate

Report

Report
Community guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
community guidelines
New Here ,
Sep 10, 2015 Sep 10, 2015

Copy link to clipboard

Copied

Hi I like to say thank you for the help. I'm just have basic knowledge and I'm learning on go. The site is just small I'm just helping a friend if you want to have a look its www.westernstmotors.co.uk. All im trying to do is a basic database and to show 30 to 50 cars and information and to show about 4 images of the car. If you know any tutorials I can work from.

many thanks

Richard

Votes

Translate

Translate

Report

Report
Community guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
community guidelines
LEGEND ,
Sep 10, 2015 Sep 10, 2015

Copy link to clipboard

Copied

LATEST

We're always here for questions when you get stuck but if you just want tutorials on PHP and MySQL, your favorite search engine will have endless amounts of them for you. I have no particular favorites myself, I honestly just like the documentation oh PHP itself. I think it does a great job of getting you up to speed. Same on MySQL.

So again, if you get stuck on a specific part like it seemed like you did, we can help with that. Teaching you PHP and MySQL overall is best left, as you said, in tutorials and documentation along with experimentation. Along your lines of learning, feel free to stop by with any questions.

Votes

Translate

Translate

Report

Report
Community guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
community guidelines