hi there,

im sorry if this has been posted before i have searched through the threads and have not found what i am looking for, however it is entirely possible that i have missed it, i have spent the whole day looking at search results and basically i need some help so if anyone can help out i would really appreciate it.

i do know there is a wealth of threads on how to upload images to a db or rather the path (which i understand to be the best course) however trying to include other data as well is just beyond my skillset and everything that i have tried.

what i am attempting to do is create an employee directory that stores text info (like: name, title, state, email, number, mobile, fact) and added to that and uploaded image (image path) to the database as well, and also how to display it. i have worked out how to do this with just text but when i get to the image part i cant seem to grasp it.

ny help would be appreciated if you need more info please ask and i will supply.

many thanks.

So are you having trouble with the actual uploading of the image to the server, or is it the combining the uploaded image info with the other form data, or other data not from a form upload, or ???

Would love to help, been working on this exact type of thing lately with a CMS I've been building for a client, just need to know where exactly you're stuck.

hi langsor,

thanks for the response. effectively what i have done is created a database table called 'employees' with 9 different columns one is the primary id and all are varchar and one blob for a textfield (other than the primary which is integer). so as mentioned before all is ok when i want to add the just a normal form data (all text) but when I want to upload an image (or the path rather) with that data that is when i get stuck. so i have no idea of how to include the path data into the form post to mysql.

Okay, let's assume you have all of your other fields with your file upload field in one form. This way you only need to manage one mysql query and not juggle two form uploads worth of data. If this is not the case, let me know and we can figure that out too.

Whenever a form uploads a file to the server, if PHP is the target form action <form action="script.php"> , then a global $_FILES array automatically gets populated with most of the data related to that file.

The file also gets uploaded to whatever temporary directory is specified in the php.ini file. This directory can not be changed with load-time/run-time configurations, you have to edit the php.ini file to change it.

When the file gets uploaded to the temp directory it also must be managed during the execution of the form-action target-script, because it also gets automatically deleted at the end of script execution. So what ever script is managing the form data needs to copy/move the file to a different location on the server if you want it to stay around.

If you were keeping the file binary data in a form field, you would definitely also need to keep the file-type and file-name in the table as well, since then you would have to set headers for that file-type and name in order to make the binary data useful again. Let me know if you end up doing this, since I recently built an image class that stores binary data and one that stores the file path. Since you're just storing the path you can probably get away with just adding one field to your existing table, otherwise I would recommend making a table just for your images and associating the images table index with the employees table records...

Here's a snapshot of what the $_FILES array might look like for a jpeg image file.

$_FILES ['userfile']['name'] => calvinhobbes.jpg
$_FILES ['userfile']['type'] => image/jpeg
$_FILES ['userfile']['tmp_name'] => C:\WINDOWS\php1D.tmp
$_FILES ['userfile']['error'] => 0
$_FILES ['userfile']['size'] => 15117

Just don't trust the file-type field of this array, since it can be spoofed and just gets its data from the file-type extension.

There's lots of details you can consider and some built in methods to handle these file uploads. You might look over the official PHP documentation too.
http://us3.php.net/features.file-upload

A couple methods include

is_uploaded_file( $_FILES ['userfile']['tmp_name']  );
move_uploaded_file( $_FILES ['userfile']['tmp_name'] , 'destination/path/picture.jpg' );

Several things to keep in mind, the form must have encoding type set and a hidden max filesize for it to do uploads

<form id="image_upload" action="image_upload.php" method="POST" enctype="multipart/form-data">
<input type="hidden" name="MAX_FILE_SIZE" value="1048576" /><!-- 1MB in bytes -->

Also, the form max filesize cannot exceed the max upload filesize in the php.ini file, which is 2MB by default -- my version. If the file it too large you will get an error #2 (2) but if it's really too large I get no error at all, it never loads far enough for an error to be set, and the form never sends any data -- so this is something to keep in mind. I use a javascript onsubmit event to test for this case and send over a $_GET value to my php script, which works pretty well for this.

I would send over a copy of my most recent scripts, but there's a lot more than image uploading, with things like automatic image resizing and what-not -- so it's kind of a code mess at the moment.

I will attach a copy of my db_image_path.php (vs image_binary) for you too look at (there's lots of room for improvement on this one, but it works), it's really for making an images database table and populating image values into it, more than actually uploading the image...

Let me know if you have any questions I'm sure to have missed here.

Cheers

Attachments
<?php
class DB_Image {
  public function __construct ( $conn = NULL ) {
    // $conn must be a database connection link resource
    // with administrative privelages to add tables ...
    // built around MySql databases, but easily modified
    if ( $conn ) {
      $this->connect( $conn );
    }
  }
  
  public function select ( $key ) {
    @mysql_free_result( $this->result );
    // for multiple results, or more sophistocated searches, perform your
    // search and proccess the images one at a time within a loop block
    // calling this function foreach unique `id` in your query results.
    $this->result = mysql_query( "SELECT * FROM `images` WHERE `key`='$key'", $this->conn );
    if ( $count = mysql_num_rows( $this->result ) ) {
      // populate image properties for object access
      // *** feel free to eliminate redundancy and/or
      //     use the naming conventions you prefer ***
      $image = mysql_fetch_object( $this->result );
      $this->key = $key;
      $this->path = $image->path;
			$this->file = $image->file;
      $this->name = $image->name;
      $this->capt = $image->caption;
      $this->caption = $image->caption;       // redundant
      $this->mime = $image->mime;
      $this->mime_type = $image->mime;        // redundant
      $this->type = $image->type;
      $this->ext = $image->type;              // redundant
      $this->extension = $image->type;        // redundant
      $this->atts = $image->attributes;
      $this->attributes = $image->attributes; // redundant
      $this->width = $image->width;
      $this->height = $image->height;
      $this->length = $image->length;
      $this->content_length = $image->length; // redundant
      $this->created = $image->created;
      $this->inserted = $image->inserted;
      $this->accessed = $image->accessed;
      $this->path = $this->make_temp();
      $accessed =  date( 'Y-m-d G:i:s', time() );
      mysql_query( "UPDATE `images` SET `accessed`='$accessed' WHERE `key`='$key'", $this->conn );
    } else {
      print( "No results for database image key: $key" ); // remove for production
    }
    return $count;
  }
  
  public function insert ( $path, $file = NULL, $name = NULL, $caption = NULL ) {
    if ( file_exists( $path ) && $info = getimagesize( $path ) ) {
		  if ( !get_magic_quotes_gpc() ) {
			  $file = addslashes( $file );
				$path = addslashes( $path );
				$name = addslashes( $name );
				$caption = addslashes( $caption );
			}
      $mime = $info['mime'];
      switch( $info[2] ) {
        case 1: $type = 'gif'; break;
        case 2: $type = 'jpg'; break;
        case 3: $type = 'png'; break;
        // view all types here: 
        // http://us.php.net/manual/en/function.exif-imagetype.php
      }
      $attributes = $info[3];
      $width = $info[0];
      $height = $info[1];
      $length = filesize( $path );
      $created = date( 'Y-m-d G:i:s', filemtime( $path ) );
      $inserted =  date( 'Y-m-d G:i:s', time() );
      $accessed =  date( 'Y-m-d G:i:s', time() );
      $result = mysql_query( "INSERT INTO `images` VALUES ( 
        NULL, '$path', '$file', '$name', '$caption', '$mime', '$type', '$attributes',
        $width, $height, $length, '$created', '$inserted', '$accessed' )", 
      $this->conn ) or die( "Could not insert image into database: ".mysql_error() );
      return mysql_insert_id( $this->conn );
    } else {
      print( "Could not find image at path: $path" ); // remove for production
      return FALSE;
    }
  }
  
  public function connect ( $conn ) { // see above
    if ( $conn ) {
      $exists = FALSE;
      $this->conn = $conn;
    } else {
      die( "Please connect to your database" );
    }
    // test for and/or create images table
    $result = mysql_query( "SELECT DATABASE()", $conn ) 
      or die ( "No database selected: ".mysql_error() );
    $dbase = mysql_result( $result, 0 );
    mysql_free_result( $result );
    $result = mysql_list_tables( $dbase, $conn );
    $count = mysql_num_rows( $result );
    for ( $i = 0; $i < $count; $i ++ ) {
      if ( mysql_tablename( $result, $i ) == 'images' ) {
        $exists = TRUE;
      }
    }
    mysql_free_result( $result );
    if ( $exists ) {
      $this->dbase = $dbase;
    } else {
      $exists = $this->create_table();
    }
    return $exists;
  }
  
  protected function create_table () {
    mysql_query( "CREATE TABLE IF NOT EXISTS `images` ( 
      `key` INT(255) UNSIGNED NOT NULL AUTO_INCREMENT,
			`path` VARCHAR(255) NOT NULL, 
			`file` VARCHAR(255) DEFAULT NULL,
      `name` VARCHAR(255) DEFAULT NULL,
      `caption` VARCHAR(255) DEFAULT NULL,
      `mime` VARCHAR(255) NOT NULL,
      `type` VARCHAR(255) NOT NULL,
      `attributes` VARCHAR(255) NOT NULL,
      `width` MEDIUMINT UNSIGNED NOT NULL,
      `height` MEDIUMINT UNSIGNED NOT NULL,
      `length` MEDIUMINT UNSIGNED NOT NULL,
      `created` DATETIME,
      `inserted` DATETIME,
      `accessed` DATETIME,
      PRIMARY KEY(`key`) )" ) 
    or die( "Could not make images table: ".mysql_error() );
    return TRUE;
  }

  public function __destruct () {
    @mysql_close( $this->conn );
  }
}
?>

hi there this is sudhir i am very thankfull to all of you giving me this help

You are very welcome.

This article has been dead for over six months. Start a new discussion instead.