Jump to content


Photo

Image Upload, rename and insert into database


  • Please log in to reply
6 replies to this topic

#1 Mutley

Mutley
  • Members
  • PipPipPip
  • Advanced Member
  • 765 posts

Posted 10 October 2006 - 11:57 AM

I have a form, one field, I want users to insert an image.

They click "Browse" chose an image they want, hit open then when they submit the form it uploads it and enters it into the database but when it uploads it I want it to be renamed to what a variable choses.

Where should I start with this? The PHP manual doesn't say anything about renaming and integrating it with a form and database:
http://us3.php.net/f...res.file-upload

Ideas?
~ Mutley.

#2 Gruzin

Gruzin
  • Members
  • PipPipPip
  • Advanced Member
  • 448 posts
  • LocationGeorgia

Posted 10 October 2006 - 01:59 PM

Well, I've done that kind of a program, I could e-mail that to you  ;)
I don't need your script, I'll try to write it myself

#3 Mutley

Mutley
  • Members
  • PipPipPip
  • Advanced Member
  • 765 posts

Posted 10 October 2006 - 02:15 PM

PM sent with e-mail. :) Thanks.
~ Mutley.

#4 Mutley

Mutley
  • Members
  • PipPipPip
  • Advanced Member
  • 765 posts

Posted 11 October 2006 - 05:58 PM

The user above hasn't got back to me, so please anyone else that can help me out?
~ Mutley.

#5 ridiculous

ridiculous
  • Members
  • PipPipPip
  • Advanced Member
  • 175 posts

Posted 11 October 2006 - 06:08 PM

Here's something to get started with:

<?php
// index.php - by Hermawan Haryanto <hermawan@dmonster.com>
// Example PHP Script, demonstrating Storing Image in Database
// Detailed Information can be found at http://www.codewalkers.com

// database connection
$conn = mysql_connect("localhost", "db", "pass")
OR DIE (mysql_error());
@mysql_select_db ("db", $conn) OR DIE (mysql_error());

// Do this process if user has browse the
// file and click the submit button
if ($_FILES) {
$image_types = Array ("image/bmp",
"image/jpeg",
"image/pjpeg",
"image/gif",
"image/x-png");
if (is_uploaded_file ($_FILES['userfile']['tmp_name'])) {
$userfile = addslashes (fread
(fopen ($_FILES["userfile"]["tmp_name"], "r"),
filesize ($_FILES["userfile"]["tmp_name"])));
$file_name = $_FILES["userfile"]["name"];
$file_size = $_FILES["userfile"]["size"];
$file_type = $_FILES["userfile"]["type"];

if (in_array (strtolower ($file_type), $image_types)) {
$sql = "INSERT INTO image "
. "(image_type, image, image_size, image_name, image_date) ";
$sql.= "VALUES (";
$sql.= "'{$file_type}', '{$userfile}', '{$file_size}', "
. "'{$file_name}', NOW())";
@mysql_query ($sql, $conn);
Header("Location:".$_SERVER["PHP_SELF"]);
exit();
}
}
}

// Do this process of user has click
// a file name to view or remove
if ($_GET) {
$iid = $_GET['iid'];
$act = $_GET['act'];
switch ($act) {
case 'view':
$sql = "select * from image where image_id=$iid";
$result = mysql_query($sql,$conn);
if (mysql_num_rows ($result)>0){
$row = @mysql_fetch_array($result);
$image_type = $row["image_type"];
$image = $row["image"];
Header("Content-type: $image_type");
print $image;
}
break;
case 'rem':
$sql = "DELETE FROM image WHERE image_id=$iid";
@mysql_query ($sql, $conn);
Header("Location:".$_SERVER["PHP_SELF"]);exit();
break;
default:
print "<img src=\"image.php?iid=$iid\">";
break;
}
}

?>
<html>
<head>
<title>Storing Images in DB</title>
</head>
<body>
<form method="post" enctype="multipart/form-data">
Select Image File:
<input type="file" name="userfile" size="40">
<input type="submit" value="submit">
</form>
<?php
$sql = "SELECT * FROM image ORDER BY image_id";
$result = mysql_query ($sql, $conn);
$i=0;
$str='';
if (mysql_num_rows($result)>0) {
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
$i++;
$str .= $i.". ";
$str .= "<a href=\"index.php?act=view&iid=".$row["image_id"]."\">"
. $row["image_name"]."</a> ";
$str .= "[".$row["image_date"]."] ";
$str .= "[".$row["image_size"]."] ";
$str .= "[<a href=\"index.php?act=rem&iid=".$row["image_id"]
. "\">Remove</a>]<br>";
}
print $str;
}
?>
</body>
</html>

#6 jvargas

jvargas
  • New Members
  • Pip
  • Newbie
  • 3 posts

Posted 11 October 2006 - 06:12 PM

Go to this website and use this PHP class it does all the uploading and resizing and more for you.

http://www.verot.net...lass_upload.htm

The databse part you would need to write your own code but here is something I have put together using the above php class.

// You will need to enter your databse information

//Lets connect to the database.
mysql_connect($server, $db_user, $db_pass) or die ("Database CONNECT Error");
mysql_select_db($database) or die ('Could not select database $db_name: ' . mysql_error());


error_reporting(E_ALL);

// we first include the upload class, as we will need it here to deal with the uploaded file
include('class.upload.php');


    // as it is multiple uploads, we will parse the $_FILES array to reorganize it into $files
// my_field is the field name you give the your HTML form field
  $files = array();
    foreach ($_FILES['my_field'] as $k => $l) {
        foreach ($l as $i => $v) {
            if (!array_key_exists($i, $files))
                $files[$i] = array();
            $files[$i][$k] = $v;
        }
    }

    // now we can loop through $files, and feed each element to the class
    foreach ($files as $file) {
   
        // we instanciate the class for each element of $file
        $execute = new Upload($file);
 
  // Check to see if files where uploaded
  if ($execute->uploaded) {
 
   
// Run the first image function   
  $execute->auto_create_dir      = true; // automatically create the directory if it does not exists
  $execute->dir_auto_chmod      = true; // change the directory permission to writable
  $execute->image_resize        = true; // If "true" resize the picture
  $execute->image_x              = 480;  // The desired width of the resize - in this case X axis
  $execute->image_ratio_y        = true; // If "true" keep the resize aspect ratio ofthe "y" property
  $execute->file_safe_name      = true; // If "true" replace spaces in the file name with "_" underscores.
  $execute-> file_autorename    = false;// If"true" automatically renames the file if it already exists.
  $execute->file_overwrite      = true; // If the file already exists overwrite it
  $execute->allowed              = array('image/jpg','image/jpeg','image/gif'); // Which type of files are allowed
  $execute->image_convert        = 'jpg';
  $execute->Process('images/users'); // Directory where the large picture will be stored
 
  // If everythig was successful display the first messasge 
  if ($execute->processed) {
    echo 'everything seems OK';
  }
  // if there is an error, display the error
  else {
    echo 'error : ' . $execute->error;
  }
 
 
// Run the second image function 
  $execute->auto_create_dir      = true; //===================================================================
  $execute->dir_auto_chmod      = true; //
  $execute->image_resize        = true; //
  $execute->image_x              = 100;  // -  read the first function for the explaination of these variables
  $execute->image_ratio_y        = true; //
  $execute->file_safe_name      = true; //
  $execute-> file_autorename    = false;//
  $execute->file_overwrite      = true; //
  $execute->allowed              = array('image/jpg','image/jpeg','image/gif');
  $execute->image_convert        = 'jpg'; //====================================================================
  $execute->Process('images/users/thumbs'); // Store the image in the users thumbs directory

  if ($execute->processed) {
    echo 'everything seems ok for the thumbs';

$filename = $execute->file_dst_name; //Get the name of the file

$execute->Clean();// Clean Up

//Get the pictures info
$query_album_info = "SELECT * FROM pictures WHERE username='$username'";
$res_album_info = mysql_query($query_album_info) ;
$album_info = mysql_fetch_assoc($res_album_info) ;
$x = 0 ;

while ($x <= 99 ) {
$x++ ;
if ($album_info['pub' . $x] == "") {
$next_available = "pub" . $x ;
$next_available_desc = "desc_pub" . $x ;
break 1 ;
}
}


//Wrtie filenames and description to the database.(table name is pictures)
$query_album_update = "UPDATE pictures SET $next_available='$filename', $next_available_desc='$filename' WHERE username='$username'" ;
$res_album_update = mysql_query($query_album_update) ;

  } else {
    echo 'error : ' . $execute->error;
  }
}
}

Hope this helps.



#7 Mutley

Mutley
  • Members
  • PipPipPip
  • Advanced Member
  • 765 posts

Posted 11 October 2006 - 08:01 PM

The code in your first post. I have a few problems.

How do I make it rename to a variable? And can I make it so inserts the full URL to the image to field in my database rather than lots of fields in a different table?

Where does it upload the images?
~ Mutley.




0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users