Click to See Complete Forum and Search --> : [RESOLVED] Need Help with inserting the correct filename from image uploads


annie_webby
01-25-2008, 03:43 PM
I'm using MySQL 5 and PHP. My database is type: MyISIAM

I am quite new to databases and MySQL (my background is design note code :o ) I have been getting some help from a consultant but this seems like it may be a pretty easy fix if someone can point me in the right direction. here's the issue:

I'm having my form submit the data directly to the database table used_aircraft then I'm having it upload the images to /Main_html/usedaircraft/uploaded_files/

It's then pulling the aircraft_id from the data and uploading that along with the image names into a table called aircraft_images

The idea was that then I could manage images and data separately but when I wanted to call the image into the "listing page" of the website I could just call the filename and insert it via and echo and php. (I sure hope that made sense)

The problem is that the filename that's being saved in the database includes several directories that I don't want included (for example: /var/www/html/Main_html/usedaircraft/uploaded_files/1201289273-N5CC_PANEL.jpg
). This means that when I pull the name it's an invalid link.

I need a way to save JUST the filename with no directory information.

Any ideas or suggestions would be greatly appreciated.

Here's the data and image insert code (Sorry about all the comments)

<?php
$username="*****";
$password="******";
$database="database_name";


$n_number=$_POST['n_number'];
$serial_number=$_POST['serial_number'];
$description=$_POST['description'];
$price=$_POST['price'];
$total_airframe_time=$_POST['total_airframe_time'];
$total_prop_time=$_POST['total_prop_time'];
$total_engine_time=$_POST['total_engine_time'];
$equipment=$_POST['equipment'];
$avionics=$_POST['avionics'];
$exterior=$_POST['exterior'];
$interior=$_POST['interior'];
$mods_conversions=$_POST['mods_conversions'];
$filename=$_POST['filename'];

mysql_connect(localhost,$username,$password);

@mysql_select_db($database) or die( "Unable to select database");

$query = "INSERT INTO used_aircraft VALUES ('','$n_number','$serial_number','$description','$price','$total_airframe_time','$total_prop_time',' $total_engine_time','$equipment','$avionics','$exterior','$interior','$mods_conversions')";

mysql_query($query);
echo(mysql_error());

$result = mysql_query("SELECT * FROM `used_aircraft` ORDER BY `aircraft_id` DESC LIMIT 1");



// make a note of the current working directory, relative to root.
$directory_self = str_replace(basename($_SERVER['PHP_SELF']), '', $_SERVER['PHP_SELF']);
//echo('server: ' . $_SERVER['PHP_SELF'] . '<br />');
//echo('directory : ' . $directory_self . '<br/>');
//echo('doc root : ' . $_SERVER['DOCUMENT_ROOT'] . '<br/>');
//echo ('replace : '. ereg_replace("^/.*/", $directory_self, "") . '<br/>');

$uploadsDirectory = $_SERVER['DOCUMENT_ROOT'] . $directory_self . 'uploaded_files/';
//echo('uploads dir : ' . $uploadsDirectory . '<br/>');

$uploadForm = 'http://' . $_SERVER['HTTP_HOST'] . $directory_self . 'aircraft_sales_entry.php';


// name of the fieldname used for the file in the HTML form
$fieldname = 'file';


// Now let's deal with the uploaded files

// possible PHP upload errors
$errors = array(1 => 'php.ini max file size exceeded',
2 => 'html form max file size exceeded',
3 => 'file upload was only partial',
4 => 'no file was attached');


// check if any files were uploaded and if
// so store the active $_FILES array keys
$active_keys = array();
foreach($_FILES[$fieldname]['name'] as $key => $filename)
{
if(!empty($filename))
{
$active_keys[] = $key;
}
}

// check at least one file was uploaded
count($active_keys)
or error('No files were uploaded', $uploadForm);

// check for standard uploading errors
foreach($active_keys as $key)
{
($_FILES[$fieldname]['error'][$key] == 0)
or error($_FILES[$fieldname]['tmp_name'][$key].': '.$errors[$_FILES[$fieldname]['error'][$key]], $uploadForm);
}

// check that the file we are working on really was an HTTP upload
foreach($active_keys as $key)
{
@is_uploaded_file($_FILES[$fieldname]['tmp_name'][$key])
or error($_FILES[$fieldname]['tmp_name'][$key].' not an HTTP upload', $uploadForm);
}


foreach($active_keys as $key)
{
@getimagesize($_FILES[$fieldname]['tmp_name'][$key])
or error($_FILES[$fieldname]['tmp_name'][$key].' not an image', $uploadForm);
}

// make a unique filename for the uploaded file and check it is
// not taken... if it is keep trying until we find a vacant one
foreach($active_keys as $key)
{
$now = time();
while(file_exists($uploadFilename[$key] = $uploadsDirectory.$now.'-'.$_FILES[$fieldname]['name'][$key]))
{
$now++;
}
}

//move the file to its final and allocate it with the new filename
foreach($active_keys as $key)
{
@move_uploaded_file($_FILES[$fieldname]['tmp_name'][$key], $uploadFilename[$key])
or error('receiving directory insuffiecient permission', $uploadForm);
}

//send $aircraft to image handling
$aircraft = mysql_result( $result, 'aircraft_id');

foreach($active_keys as $key)
{
if(!empty($uploadFilename[$key]))
{

$query = "INSERT INTO aircraft_images VALUES ('','$aircraft','','$uploadFilename[$key]')";
mysql_query($query);
echo(mysql_error());
}
}

//header('Location: ' . $uploadSuccess);
//header('Location: aircraft_entry_success.php');

function error($error, $location, $seconds = 5)
{
//header("Refresh: $seconds; URL=\"$location\"");
echo '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"'."\n".
'"http://www.w3.org/TR/html4/strict.dtd">'."\n\n".
'<html lang="en">'."\n".
' <head>'."\n".
' <meta http-equiv="content-type" content="text/html; charset=iso-8859-1">'."\n\n".
' <link rel="stylesheet" type="text/css" href="stylesheet.css">'."\n\n".
' <title>Upload error</title>'."\n\n".
' </head>'."\n\n".
' <body>'."\n\n".
' <div id="Upload">'."\n\n".
' <h1>Upload failure</h1>'."\n\n".
' <p>An error has occured: '."\n\n".
' <span class="red">' . $error . '...</span>'."\n\n".
' The upload form is reloading</p>'."\n\n".
' </div>'."\n\n".
'</html>';
exit;
} // end error handler

?>

Thanks in advance for any suggestions!

jasonahoule
01-25-2008, 04:09 PM
If you are keeping the name of the file that is uploaded then that is the value you should be inserting into the database. $_FILES[xxx]['name'].

I would suggest at least stripping out any spaces, quotes, and other special characters.

annie_webby
01-25-2008, 04:18 PM
If you are keeping the name of the file that is uploaded then that is the value you should be inserting into the database. $_FILES[xxx]['name'].

I would suggest at least stripping out any spaces, quotes, and other special characters.

Thanks for the help. Sorry to be dense here but...

Is this where i'd use that? And what do I need to feed in instead of xxx.

foreach($active_keys as $key)
{
if(!empty($uploadFilename[$key]))
{
$query = "INSERT INTO aircraft_images VALUES ('','$aircraft','','$_FILES[xxx]['name']
')";
//$query = "INSERT INTO aircraft_images VALUES ('','$aircraft','','$uploadFilename[$key]')";
mysql_query($query);
echo(mysql_error());
}
}

jasonahoule
01-25-2008, 04:33 PM
The xxx should be the name of the file field in your form.

annie_webby
01-25-2008, 05:16 PM
Ok... i getcha.

So I put this in:

$query = "INSERT INTO aircraft_images VALUES ('','$aircraft','','$_FILES[$fieldname]['name'][$key]')";

and now I get:

You have an error in your SQL syntax near 'name'][0]')' at line 1You have an error in your SQL syntax near 'name'][1]')' at line 1

when I run it.

Any ideas what's going on?

jasonahoule
01-25-2008, 09:46 PM
Watch out for your quotes...
Try this:

$query = "INSERT INTO aircraft_images VALUES ('','$aircraft','','".$_FILES[$fieldname]['name']."')";

annie_webby
01-28-2008, 09:54 AM
-facepalm- I'm SO bad about quotes. Thanks for noticing that.

Now the query mostly works but it's just saving the word "array" instead of the filename. I'm guessing it's the way my image handling works as it uploads the images as an array.

Any ideas or is this getting to the point where I need some more intensive help ':)

thanks again!

EDIT: Ok I reinserted the "[$key]" and now it inserts the original filename. Now if only I could get it to insert the NEW filename (with the numbers in front) it would be PERFECT!

jasonahoule
01-28-2008, 10:15 AM
Oops, sorry. I guess I wasn't following your logic there. I will take a look again.

jasonahoule
01-28-2008, 10:19 AM
Ok, now I am confused. How do you have multiple fields with the same name in a single form? Ok, here is what I would do since you already have your $uploadFilename array populated.


foreach($uploadFilename as $path) {
$pathArray = split('/', $path);
$file = $pathArray[count($pathArray) -1];
}


I would suggest using mysql_last_insert_id to get your id rather than calling back everything and sorting. You will most definitely run into problems farther down the line. If you have two people that do an insert at the same time then you will have everything all mixed up.

annie_webby
01-28-2008, 12:35 PM
That bit of code DEFINITELY was a step in the right direction! I feel like it's almost resolved.

That one got me the correct filename with no path attached. Unfortunately it just repeated the same filename for each of the entries but now I just need to get it to run through the array and insert the correct filenames.

I really appreciate all the suggestions. I'll definitely change this:

I would suggest using mysql_last_insert_id to get your id rather than calling back everything and sorting. You will most definitely run into problems farther down the line. If you have two people that do an insert at the same time then you will have everything all mixed up.

as well. Like I mentioned I'm pretty new to SQL and database handling so I bet I do things the dumb way alot.

Now I'm going to try to get the right filename for each field.

Thanks