Current location: Hot Scripts Forums » Programming Languages » PHP » need help with upload image and getting image name to db


need help with upload image and getting image name to db

Reply
  #1 (permalink)  
Old 05-14-04, 10:45 AM
mikewooten mikewooten is offline
Newbie Coder
 
Join Date: Feb 2004
Posts: 17
Thanks: 0
Thanked 0 Times in 0 Posts
need help with upload image and getting image name to db

i'm using this upload code below.
i am a student working on an ecommerce project
i have an ecommerc website and an admin on the page that i have, i'm working on the admin part at the moment.
i want the admin to enter info into all of the fields that are provided such as the item name, item description, and item price, and item image.
here is the site that i'm working on for an example

http://www.wootenmedia.com/wootenmus...t/add3_1_3.php

i would like the name to be inserted into the datbase in order for the image to show up on the ecommerc website on the products pages here is my ecommerce site i have

http://www.wootenmedia.com/wootenmusic7/guitars.php

can anyone help me out in getting the image name, which is being uploaded, to the database so that the image will show up on the products page of the ecommmerce website any help would be appreciated.
thanks
this is the code that i'm using for uploading the image and inserting the image into the database:


PHP Code:



<?
header
("Cache-Control: no-store, no-cache, must-revalidate");
header("Cache-Control: post-check=0, pre-check=0"false);
header("Pragma: no-cache");
header("Last-Modified: " gmdate("D, d M Y H:i:s") . " GMT");
?>
<?php 
echo "<?xml version=\"1.0\" encoding=\"iso-8859-1\"?".">"?>
<!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>
<title>Untitled Document</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<META HTTP-EQUIV='Pragma' CONTENT='no-cache' />
<META HTTP-EQUIV='Cache-Control' CONTENT='no-cache' />
</head>
<body>
<form action="<? $_SERVER['PHP_SELF']; ?>" method="post" ENCTYPE="multipart/form-data"> 
Choose a product category  <br>
<select name="txtCatID" id="select">
                    <option value="0" SELECTED>0</option>
                    <option value="1">1</option>
                    <option value="2">2</option>
                    <option value="3">3</option>
</select><br>  
Choose product items to add to your product pages  <br>
   <input type="hidden" name="<?echo '$txtCatID';?>">
<select name="txtprodItems" id="select">
                    <option value="Guitars" SELECTED>Guitars</option>
                    <option value="Drums">Drums</option>
                    <option value="Amps">Amps</option>
                    <option value="Books">Books</option>
</select><br>
item name<br>
<input type="text" name="txtItemName"><br>
item description<br>
<input type="text" name="txtItemDesc"><br>
item price<br>
<input type="text" name="txtItemPrice"><br>
<?
//START DB Stuff Here////////////////
    // specify the directory where the uploaded file should end up 
    
$path "/home/username/public_html/wootenmusic7/p_imgs/";
// specify the filetypes allowed 
$allowed = array('image/gif','image/pjpeg','image/jpeg','image/png'); 
// specify the max filesize in bytes 
$max_size 200000
if(isset(
$_FILES['txtItemImage'])) 

  if(
is_uploaded_file($_FILES['txtItemImage']['tmp_name'])) 
  { 
   if(
$_FILES['txtItemImage']['size'] < $max_size
   { 
    if(
in_array($_FILES['txtItemImage']['type'],$allowed)) 
    { 
     if(!
file_exists($path $_FILES['txtItemImage']['name'])) 
     { 
      if(
move_uploaded_file($_FILES['ItemImage']['tmp_name'],$path.$_FILES['txtItemImage']['name'])) 
      { 
       
$html_output 'Upload sucessful!<br>'
       
$html_output .= 'File Name: '.$_FILES['txtItemImage']['name'].'<br>'
       
$html_output .= 'File Size: '.$_FILES['txtItemImage']['size'].' bytes<br>'
       
$html_output .= 'File Type: '.$_FILES['txtItemImage']['type'].'<br>'
       
$image $_FILES['txtItemImage']['name'] ; 
      }else{ 
       
$html_output 'Upload failed!<br>'
       if(!
is_writeable($path)) 
       { 
        
//$html_output = 'The Directory "'.$path.'" must be writeable!<br>'; 
       
}else{ 
        
$html_output 'an unknown error ocurred.<br>';       
       } 
      } 
     }else{ 
      
$html_output 'The file already exists<br>'
     } 
    }else{ 
     
$html_output 'Wrong file type<br>'
    } 
   }else{ 
    
$html_output 'The file is too big<br>'
   } 
  } 
}else{ 
  
$html_output '<form method="post" enctype="multipart/form-data" action="'.$_SERVER['PHP_SELF'].'">'
  
$html_output .= '<input type="file" name="txtItemImage">'
  
$html_output .= '<input type="submit" name="submit" value="upload"><input type="Reset" />'
  
$html_output .= '</form>'

echo 
'<html><head><title>Uploader</title></head><body>'
echo 
$html_output
echo 
'</body></html>'
   
$html_output $_POST['submit'];
      if(isset(
$html_output)){
    include(
"db2.php");    
    
// Get a connection to the database
    
$cxn = @ConnectToDb($dbServer$dbUser$dbPass$dbName);            
            
$txtCatID $_POST['txtCatID'];
            
$txtprodItems $_POST['txtprodItems'];
            
$txtItemName $_POST['txtItemName'];
            
$txtItemDesc $_POST['txtItemDesc'];
            
$txtItemPrice $_POST['txtItemPrice'];           
            
$txtItemImage $_FILES['txtItemImage']['name'];
echo 
"$theSQL";
$theSQL "insert into items (prodItems, catid, itemName, itemDesc, itemPrice, ItemImage)";
$theSQL $theSQL " values ('$txtprodItems', '$txtCatID', '$txtItemName', '$txtItemDesc', '$txtItemPrice', '$txtItemImage')";
    
$result mysql_query($theSQL); 
    echo 
"$theSQL";
    }else{
    echo 
"did not insert any image into database";
    } 
?>
Digg this Post!Add Post to del.icio.usBookmark Post in TechnoratiShare on FacebookShare on Stumble UponShare on Twitter
Reply With Quote
  #2 (permalink)  
Old 05-14-04, 11:32 AM
NeverMind's Avatar
NeverMind NeverMind is offline
Community VIP
 
Join Date: Aug 2003
Location: K.S.A
Posts: 2,257
Thanks: 0
Thanked 2 Times in 1 Post
well, you have these lines:
PHP Code:

$image $_FILES['txtItemImage']['name'];

//and
$txtItemImage $_FILES['txtItemImage']['name']; 
they have the file name !
also in your INSERT query, you have used the second var $txtItemImage! what's the problem? it should insert the name!
__________________
PHPSimplicity
We don't need a reason to help people - Zidane [FF9]

Last edited by NeverMind; 05-14-04 at 11:35 AM.
Digg this Post!Add Post to del.icio.usBookmark Post in TechnoratiShare on FacebookShare on Stumble UponShare on Twitter
Reply With Quote
  #3 (permalink)  
Old 05-14-04, 12:44 PM
Bonzo's Avatar
Bonzo Bonzo is offline
Coding Addict
 
Join Date: Jan 2004
Posts: 340
Thanks: 0
Thanked 0 Times in 0 Posts
This line works OK for me

mysql_query ( "INSERT INTO photos ( image ) VALUES ('$filename' )" )

photos = database, image = column name, $filename = the name of the image

Trouble is I can never read anyone elses code as well as mine : (
PHP Code:

// This is the line I use in my form as well

<form enctype='multipart/form-data' action='$PHP_SELF' method='post'
How about just trying a simple upload and get rid of all the " if " & " else " to get it working first ?

Anthony

P.S. To the cleverer here than me ( most others here and defiinatly NeverMind ! ).

Would it be possible to do away with all the if & elses and use a/some functions instead ? I have yet to learn/get one to work yet.

Last edited by Bonzo; 05-14-04 at 12:55 PM.
Digg this Post!Add Post to del.icio.usBookmark Post in TechnoratiShare on FacebookShare on Stumble UponShare on Twitter
Reply With Quote
  #4 (permalink)  
Old 05-14-04, 05:52 PM
mdhall's Avatar
mdhall mdhall is offline
Aspiring Coder
 
Join Date: Oct 2003
Posts: 510
Thanks: 1
Thanked 1 Time in 1 Post
Something basic, but it works for me. Upload.php adds the info to a database, randomly renames the file, and uploads the file to a directory. Allows only jpg's, checks that all fields are filled in. Change"my_site/photos" to where the files will be stored. Checks for max file size and incorrect file type. Need to change your database connection values, the table name, and the page to redirect to.

The form...

<form enctype="multipart/form-data" action="upload.php" method="post">
Your name:
<br>
<input type="text" name="fname" size="20"><p>
Title of Photo:<br>
<input type="text" name="title" size="40"><p>
Description<br>
<textarea name="desc" cols="50" rows="2"></textarea><p>
Select a Photo....jpg only<p>
<input type="file" name="upfile">
<p>
<input type="submit" name="submit" value="Add Photo">
<input type="reset" name="reset" value="Reset">
</form>

upload.php
PHP Code:

 
     $file_types 
= array(   
     
'image/pjpeg' => 'jpg'
     
'image/jpeg' => 'jpg'
    ); 
     
$fname=$_POST['fname']; 
     
$title=$_POST['title'];
     
$desc=$_POST['desc'];
    
    
     
$max_size 1024000;
     
$filesize $_FILES['upfile']['size'];
     
$filetype $_FILES['upfile']['type'];
     
$upload_dir $_SERVER['DOCUMENT_ROOT'] . "/my_site/photos/"
       if((!
$fname) || (!$title) || (!$desc)){
 echo 
'You did not submit the following required information. Use your browsers "back" button to complete your form. <br />';
 if(!
$fname){
  echo 
"Name is a required field. <br />";
 }
 if(!
$title){
  echo 
"Photo title is a  required field. <br />";
 
 }
              if(!
$desc){
  echo 
"Photo description is a  required field. <br />";
 
 }
               }else{
       
        if (
$filesize $max_size){
           
header ("location: size_error.php");
           exit;
        }
         if (!
array_key_exists($filetype$file_types)) { 
                
header ("location: type_error.php"); 
            exit;
        } 
        else
        {   
                
$new_file substr(sha1(rand(10time())), 08) . '.' $file_types[$filetype]; 
               if (
move_uploaded_file($_FILES['upfile']['tmp_name'], $upload_dir $new_file)) { 
                 
              
$filename=$new_file;
               
$dbuser="your user name";
$dbpass="your password"
$database="database name";
                            
$conn mysql_connect(localhost,"$dbuser","$dbpass") or die ("Could not connect to MySQL"); 
              
mysql_select_db("$database") or die ("Could not open database"); 
              
$query "INSERT INTO table_name VALUES('','$fname','$title','$desc','$filename')"
              
$result=mysql_query($query); 
      }
   }
mysql_close(); 
header ('Location: redirect page.ext');

Let me know if it works for you.
Digg this Post!Add Post to del.icio.usBookmark Post in TechnoratiShare 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


All times are GMT -5. The time now is 01:22 PM.
vBulletin® Copyright ©2000 - 2012, Jelsoft Enterprises Ltd.