Current location: Hot Scripts Forums » Programming Languages » PHP » Upload file to table so ONLY files tied to primary key are displayed in record?

Upload file to table so ONLY files tied to primary key are displayed in record?

Reply
  #1 (permalink)  
Old 12-13-03, 03:06 PM
grafixDummy grafixDummy is offline
New Member
 
Join Date: Dec 2003
Posts: 4
Thanks: 0
Thanked 0 Times in 0 Posts
Upload file to table so ONLY files tied to primary key are displayed in record?

Hello all, I hope this makes sense. I'm a ponytail in a propellerhead world.

I'm looking for an example of code to upload/insert an image file to a field of a table and have only the files associated with the primary key of the table be displayed in the detail view as download links.

I've found and got wirking many examples of uploaders that put the files into a directory, but in detail view of the table (got that working too), ALL files in the directory are listed as downloads because the scripts I have working don't use mysql to relate individual files to a record. Not what I want. I need each record to only display links to only files associated with that record, not the whole directory.

Am I thinking about this the right way? or should I be getting info (path/mime type, name, etc..) from the file and inserting that info (maybe as an array?) into mysql table and then displaying the PATH to the file (still sitting in the directory with all the others) as a link tied to the primary key of the table?

The first way sounds easier (would I use blob?), but something tells me the second way is better. I'm not the brightest bulb when it comes to coding (as my name implies), but I'm good with examples to modify.

I knows its lots of questions, but any reply would be GREATLY appreciated.
Digg this Post!Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!Share on FacebookShare on Stumble UponShare on Twitter
Reply With Quote
  #2 (permalink)  
Old 12-13-03, 05:29 PM
blaw's Avatar
blaw blaw is offline
Junior Code Guru
 
Join Date: Dec 2003
Location: Vancouver, BC, Canada
Posts: 550
Thanks: 0
Thanked 0 Times in 0 Posts
Hi there,

You said
Quote:
Originally Posted by grafixDummy
......have only the files associated with the primary key of the table be displayed in the detail view as download links.
And then
Quote:
Originally Posted by grafixDummy
......the scripts I have working don't use mysql to relate individual files to a record. Not what I want.
These two seem conflicting to me. So arwe you using MySQL (or any kind of database) to store the image file path/names?
__________________
Blavv =|
Digg this Post!Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!Share on FacebookShare on Stumble UponShare on Twitter
Reply With Quote
  #3 (permalink)  
Old 12-13-03, 08:22 PM
grafixDummy grafixDummy is offline
New Member
 
Join Date: Dec 2003
Posts: 4
Thanks: 0
Thanked 0 Times in 0 Posts
blah said:
Quote:
These two seem conflicting to me. So arwe you using MySQL (or any kind of database) to store the image file path/names?
Thanks for the reply!

I AM using mysql (local WAMP setup) for the dat entry/retrieval part of the application, but not for the files. I'm okay on simple text inserting/selecting, but not on file management. I've got php Advanced Transfer Manager running for that. phpATM doesn't use mysql, it just uploads to a directory and makes a slug file containing some info about the file and keeps it in the same directory as the uploaded file. The script then lists all the files in that directory for download. No mysql connection even made.

What you're describing is exactly what I'm looking for... a snippet of code that will store image file path/names in a table and the query to list those files as download links.

I wanted to get this done before school starts again, but all the scripts I find for both file upload/download store in a flat table that I can't relate to my master_id. Hope this isn't too stupid of questions. I'm really not a programmer, but the more i learn about php, the more I want to know cuz its fun when you finally get something to work
Digg this Post!Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!Share on FacebookShare on Stumble UponShare on Twitter
Reply With Quote
  #4 (permalink)  
Old 12-13-03, 11:20 PM
blaw's Avatar
blaw blaw is offline
Junior Code Guru
 
Join Date: Dec 2003
Location: Vancouver, BC, Canada
Posts: 550
Thanks: 0
Thanked 0 Times in 0 Posts
Hi there,

Thanks for clarification.

So this phpATM thing uploads files into one directory and add an info about this image into a text file (or whatever the extention it may be).

Then when you show the available downloads on another page, you read this file and display the names and corresponding links to them.

But the problem is that you want to show the files that are specifically requested - maybe something like this:

On the first page where you have a list of the files, users can click on a single image link that they want to view more details about. The link is something like a href="detail.php?id=123", and when the users arrive at detail.php, you want them to see only the image(s) that the parameter specifies, and not all of them). BUT because the file path/name are all in the text file that phpATM created and there is no database, you can't pass the criterion (i.e. $_GET['id']).

Is this correct?

If so, there are two ways to achieve this.

1) Store file path/name (upon uploading) into a MySQL table. If there can be more than one image that is associated with your PK, then use a separate table (i.e. one-to-many relationship, using the main table's PK as FK). This requires MySQL connection upon uploading, of course.

2) Depending on how this file created by phpATM is organized, you can try to "query out" those that are "associated" with your PK by reading the text file and compare it with the criterion. This will NOT require any database connection per se. If this is what you prefer, but don't know how to start with it, if you can give me a more specific example (especially how the text file is organized), I may be able to help you.

And finally, remember that there is no stupid question.
__________________
Blavv =|

Last edited by blaw; 12-13-03 at 11:24 PM.
Digg this Post!Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!Share on FacebookShare on Stumble UponShare on Twitter
Reply With Quote
  #5 (permalink)  
Old 12-20-03, 05:28 PM
grafixDummy grafixDummy is offline
New Member
 
Join Date: Dec 2003
Posts: 4
Thanks: 0
Thanked 0 Times in 0 Posts
blah said
Quote:
2) Depending on how this file created by phpATM is organized, you can try to "query out" those that are "associated" with your PK by reading the text file and compare it with the criterion. This will NOT require any database connection per se. If this is what you prefer, but don't know how to start with it, if you can give me a more specific example (especially how the text file is organized), I may be able to help you.
Yes. Thank you, this is what I've decided on, but phpATM stores file info into mnay different txt files (one for each uploaded file) so I pieced something else together with a sniff script and simple uploader.

This is what I've got so far. I need a way to write ads.ad_id ($x primary key of query) and other file info (name, type) as a description into the "sniff" script descript.ion file on upload and only display download link for the files that match ads.ad_id and allow upload only when there is a ads.ad_id value present.



///Here is the main page of the application
<?php


include("./lib.php");
include("./ads_dml.php");

$x = new DataList;
if($HTTP_POST_VARS["Filter_x"] != "")
{
// Query used in filters page
$x->Query = "select ads.ad_id as 'Ad#', ads.cust_name as 'Customer', ads.cust_address as 'Address', ads.cust_phone as 'Phone', pub_dates5.pubs as 'Pub Date', ad_states6.states as 'Ad State', color_depth7.colors as 'Ad Color', ad_sizes8.ad_sizes as 'Ad Size', ads.new_ad as 'Is this a new ad?', ads.ref_ad as 'Reference Ad# (list all)', ads.sell_type as 'Sell Type?', ads.layout_type as 'Layout Type', ads.layout_coming as 'Hard Copy Coming?', ads.files as 'Files Coming Via:', ads.header as 'Header:', ads.offers as 'Offers:', ads.instruction as 'Instruction' from ads, pub_dates as pub_dates5, ad_states as ad_states6, color_depth as color_depth7, ad_sizes as ad_sizes8 where ads.pub_date=pub_dates5.pub_date_id and ads.ad_state=ad_states6.ad_state_id and ads.ad_color=color_depth7.color_depth_id and ads.ad_size=ad_sizes8.ad_size_id";
}
else
{
// Query used in table view
$x->Query = "select ads.ad_id as 'Ad#', ads.cust_name as 'Customer', pub_dates5.pubs as 'Pub Date', ad_states6.states as 'Ad State', color_depth7.colors as 'Ad Color', ad_sizes8.ad_sizes as 'Ad Size' from ads, pub_dates as pub_dates5, ad_states as ad_states6, color_depth as color_depth7, ad_sizes as ad_sizes8 where ads.pub_date=pub_dates5.pub_date_id and ads.ad_state=ad_states6.ad_state_id and ads.ad_color=color_depth7.color_depth_id and ads.ad_size=ad_sizes8.ad_size_id";
}
$x->DataHeight = 75;
$x->AllowSelection = 1;
$x->AllowDelete = 1;
$x->AllowInsert = 1;
$x->AllowUpdate = 1;
$x->AllowFilters = 1;
$x->AllowSorting = 1;
$x->AllowNavigation = 1;
$x->AllowPrinting = 1;
$x->AllowCSV = 0;
$x->HideTableView = 0;
$x->RecordsPerPage = 5;
$x->QuickSearch = 1;
$x->QuickSearchText = "Quick search";
$x->ScriptFileName = "index.php";
$x->TableTitle = "AD MANAGER";
$x->PrimaryKey = "ads.ad_id";
$x->ColWidth[] = 50;
$x->ColWidth[] = 150;
$x->ColWidth[] = 75;
$x->ColWidth[] = 75;
$x->ColWidth[] = 75;
$x->ColWidth[] = 50;
$x->Render();

echo $x->HTML;
//
//
//This is to call the sniff script that lists all files in the directory
//
//
//


include("/upload/index.php");


//
//
//
// This is the uploader to the same directory
///
///
////
/////
//////

include('class_file_upload.php');

$destination_dir = '';

$extensions = array(
'exe',
'php',
'php3',
'php4',
'phtml',
'cgi',
'pl'
);

$u = new file_upload('C:/FoxServ/www/phprojekt/addons/AdManager');

// delete file
if (isset($_GET['delete'])) {

if (!$u->delete_file($_GET['delete'], $destination_dir)) {

echo "error: " . $u->error;
} else {

echo $_GET['delete'] . " deleted successfully.";
}
}

// upload file
if (count($_FILES) > 0) {

if (!$u->upload($_FILES['myfile'], $destination_dir, 2, $extensions, 1)) {

echo "error: " . $u->error . "<br>\n<br>\n";
echo "Debug: <br>\n";
echo "base_dir: ". $u->base_dir ."<br>\n";
echo "dest_dir: ". $u->dest_dir ."<br>\n";
echo "max_upload_size: ". $u->max_upload_size ."<br>\n";
echo "extensions_mode: ". $u->extensions_mode ."<br>\n";
echo "extensions: <pre>";
var_dump($u->extensions);
echo "</pre>";
echo "copy_mode: ". $u->copy_mode ."<br>\n";
echo "copy_label: ". $u->copy_label ."<br>\n";

} else {

echo "no errors! uploaded ". $u->file['name'] .".<br>\n";
echo "<a href=\"example.php?delete=". $u->file['name'] ."\">delete it?</a>";
}
}

?>
<br>
<br>
<form action="example.php" method="post" enctype="multipart/form-data" >
<input type="file" name="myfile">
<input type="submit" value="Send">
</form>
</body>

</html>


/////
///// Here is a description of the sniff file descript.ion file

************************************************** **************************
** DESCRIPTION FILE FORMAT **
************************************************** **************************

Hardcore definition:

<descriptionfile> ::= <line>*
<line> ::= <filename><separationString><description><EOL>
<filename> ::= <anythingExceptSeparationString>+
<separationString> ::= defined by the $separationString variable, default "\t"
<description> ::= <anyting>+
<EOL> ::= "\r\n" | "\n" // OS dependent


Simple example:

. This directory contains downloadable files for MyProgram 12.0.
myprogram_12.0.exe Installer version of MyProgram 12.0 (recommended)
myprogram_12.0.zip Zip file distribution of MyProgram 12.0
releasenotes.txt Release notes for MyProgram 12.0


Please note that the room between the filename and the description is not
filled with multiple spaces, but with one single tab. It doesn't matter if
the descriptions in a file align or not, just use one tab.
If you use a description for the current directory (.) as in the first line
in the above example, it will be used as a heading in the directory listing.




/////
////
//// And here is the class_file_upload include file
<?php
#----------------------------------------------------------------------#
# $Id: class_file_upload.php,v 1.3 2003/03/02 13:07:26 timo Exp $
#================================================= =====================#
# Author: Timo Reith <timo@ifeelweb.de>
#----------------------------------------------------------------------#

/**
* Class to handle file uploads by timo@ifeelweb.de
* Features:
* - allow or block file extensions
* - three different copy modes (consider existing files)
* - detailed error reporting
* - set filesize limit
*/

class file_upload {

/**
* base directory, where your main application is running
*/
var $base_dir = 'C:/FoxServ/www/phprojekt/addons/AdManager';

/**
* where the uploaded file should be copied to, relative to $base_dir
*/
var $dest_dir = '';

/**
* internal filesize limitation in bytes, 0 = off, php.ini limit always rules
*/
var $max_upload_size = 0;

/**
* how to treat $extensions, 1 = block 2 = allow extensions in $extensions array
*/
var $extensions_mode = 1;

/**
* list of file extensions
*/
var $extensions = array();

/**
* how to handle uploads, 0 = don't overwrite existing file, 1 = rename existing file (see $copy_label), 2 = overwrite
*/
var $copy_mode = 0;

/**
* if copy mode is 1, $copy_label + n will be appended to existing file
*/
var $copy_label = '_copy';

/**
* error return message
*/
var $error = '';

/**
* indicates if class was initialized correctly
*/
var $init = 1;

/**
* all parameters of the file to be uploaded like in $_FILES, see $file_info also
*/
var $file = array();

/**
* list of needed parameters for internal validation
*/
var $file_info = array('name','type','size','tmp_name','error');


/**
* file_upload - constructor
*
* @param string $base_dir - base directory
* @param int $max_upload_size - internal filesize limitation in bytes
*
* @return
*
* @access public
*/
function file_upload ($base_dir = false, $max_upload_size = false) {

if ($base_dir == true) {
if ($dir = $this->check_dir($base_dir)) {
$this->base_dir = $dir;
} else {
return false;
}
}
if ($max_upload_size == true) {
$this->max_upload_size = $max_upload_size;
}
}


/**
* upload - main upload method
*
* @param array $file - array of file data like $_FILES
* @param string $dest_dir - directory to copy the uploaded file to
* (relative to $base_dir)
* @param int $copy_mode - how to handle uploads
* @param array $extensions - list of file extensions
* @param int $extensions_mode - how to treat $extensions
*
* @return boolean - true if upload was successful
*
* @access public
*/
function upload ($file, $dest_dir = false, $copy_mode = false,
$extensions = false, $extensions_mode = false) {

if ($this->init != 1) {
$this->error_msg("error in class initialization");
return false;
}

$this->error = '';

// check if destination dir exists
if ($dest_dir == true) {
if ($dir = $this->check_dir($dest_dir, $this->base_dir)) {
$this->dest_dir = $dir;
} else {
return false;
}
}

// check if $file is array
if (!is_array($file)) {
$this->error_msg("error in submitting file parameters (not an array)");
return false;
}

// check if all file parameters were submitted
foreach ($this->file_info as $v) {
if (!isset($file[$v])) {
$this->error_msg("Missing parameter $v");
return false;
}
}

$this->file = $file;

if ($copy_mode == true) {
$this->copy_mode = $copy_mode;
}
if ($extensions == true) {
if (!is_array($extensions)) {
$extensions = array($extensions);
}
$this->extensions = $extensions;
}
if ($extensions_mode == true) {
$this->extensions_mode = $extensions_mode;
}

// check $_FILES error segment
if ($this->check_upload_error() != true) {
return false;
}

// check file size
if ($this->check_upload_size() != true) {
return false;
}

// get file extension
$this->file['ext'] = $this->get_ext();

// check if file type is allowed for upload
if ($this->check_extensions() != true) {
return false;
}

// check if file comes via HTTP POST
if (!is_uploaded_file($this->file['tmp_name'])) {
$this->error_msg("No HTTP POST Upload");
return false;
}

// copy the file considering copy mode
switch ($this->copy_mode) {

case 0: // don't move if file already exists
if (file_exists($this->base_dir . $this->dest_dir . $this->file['name'])) {
$this->error_msg("file ". $this->file['name'] ." already exists");
return false;
} else {
return $this->move_file();
}
break;

case 1: // rename file if already exists
$n = 1;
$split = explode(".".$this->file['ext'], $this->file['name']);
while(file_exists($this->base_dir . $this->dest_dir . $split[0] .
$add . "." . $this->file['ext'])) {

$add = $this->copy_label . $n;
$n++;
}
$this->file['name'] = $split[0] . $add . "." . $this->file['ext'];
return $this->move_file();
break;

case 2: // overwrite existing file
return $this->move_file();
break;

default:
$this->error_msg("invalid copy mode");
return false;
break;
}
}


/**
* move_file - moves the file from upload temp dir to destination dir
*
* @return bool
*
* @access private
*/
function move_file () {

// move file to destination
if (!@move_uploaded_file($this->file['tmp_name'], $this->base_dir .
$this->dest_dir . $this->file['name'])) {

$this->error_msg("file could not be copied to ". $this->dest_dir);
return false;
} else {
return true;
}
}


/**
* delete_file
*
* @param string $del_file - file to delete
* @param string $dest_dir - directory which contains file to delete
*
* @return bool
*
* @access public
*/
function delete_file ($del_file, $dest_dir = false) {

// check if dest dir exists
if ($dest_dir == true) {
if ($dir = $this->check_dir($dest_dir, $this->base_dir)) {
$this->dest_dir = $dir;
} else {
return false;
}
}

if (!@unlink( $this->base_dir . $this->dest_dir . $del_file )) {
$this->error_msg("file $del_file could not be deleted");
return false;
} else {
return true;
}
}


/**
* check_dir - check if a directory does exist
*
* @param string $dir - dir to check
* @param string $path - path to dir
*
* @return bool
*
* @access private
*/
function check_dir ($dir, $path = false) {

if (is_dir($path . $dir)) {
$return_dir = (substr($dir, -1) == "/") ? $dir : $dir . "/";
return $return_dir;
} else {
$this->error_msg("dir $path$dir does not exist");
$this->init = 0;
return false;
}
}


/**
* check_upload_error - checks $_FILES error segment
*
* @param
*
* @return bool
*
* @access private
*/
function check_upload_error () {

switch ($this->file['error']) {
case 0:
return true;
case 1:
$this->error_msg("php.ini filesize exceeded");
return false;
break;
case 2:
$this->error_msg("html filesize exceeded");
return false;
break;
case 3:
$this->error_msg("file uploaded partly");
return false;
break;
case 4:
$this->error_msg("no file delivered");
return false;
break;
}
}


/**
* check_upload_size
*
* @param
*
* @return bool
*
* @access private
*/
function check_upload_size () {

if ($this->max_upload_size == true && $this->file['size'] > $this->max_upload_size) {
$this->error_msg("upload exceeded " . $this->max_upload_size . " Bytes");
return false;
} else {
return true;
}
}


/**
* check_extensions - checks if file extension is allowed for upload
*
* @param
*
* @return bool
*
* @access private
*/
function check_extensions () {

if ( (in_array($this->file['ext'], $this->extensions) && $this->extensions_mode == 1)
|| (!in_array($this->file['ext'], $this->extensions) && $this->extensions_mode == 2) ) {

$this->error_msg("upload of ". $this->file['ext'] ."-files not allowed");
return false;
} elseif ($this->extensions_mode != 1 && $this->extensions_mode != 2) {
$this->error_msg("invalid extension mode");
return false;
} else {
return true;
}
}


/**
* get_ext - get the file extension
*
* @param
*
* @return string extension
*
* @access private
*/
function get_ext () {

return strtolower(substr(strrchr( $this->file['name'], '.' ), 1 ));
}


/**
* error_msg - collects the error messages
*
* @param string $error_msg - error message
*
* @return void
*
* @access private
*/
function error_msg ($error_msg) {

if (!empty($this->error)) {
$this->error .= " & " . $error_msg;
} else {
$this->error = $error_msg;
}
}
}
?>



The upload works but right now the sniff script defaults to list all files in the directory, but I can point it to the description file to derive all of its values so only the files uploaded and written to the description file can be seen as downloads. I would like to further filter the results by only showing the files whose description matches the ads.ad_id (primary key which is written to the description file when uploaded)



Any Help Would Be Greatly Appreciated!
Digg this Post!Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!Share on FacebookShare on Stumble UponShare on Twitter
Reply With Quote
Reply

Bookmarks


Currently Active Users Viewing This Thread: 1 (0 members and 1 guests)
 
Thread Tools
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is Off
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are On

Forum Jump

Similar Threads
Thread Thread Starter Forum Replies Last Post
Use an EXCEL file to update a table in MSSQL busypanda ASP.NET 0 11-12-03 09:51 AM
Upload file type and size limiter! Arctic ASP 1 08-02-03 08:06 PM


All times are GMT -5. The time now is 08:50 PM.
vBulletin® Copyright ©2000 - 2009, Jelsoft Enterprises Ltd.