update image path and upload the image

Discussion in 'PHP' started by macaela, Oct 1, 2011.

  1. #1
    Hi i know how to update normal data without image, i also know how to upload image and insert path into database but now i am trying to put together both to update path and insert image into database field but just as a start i when i try update the file path on the database it just inserts the word array.
    can someone help me put together the update and image upload
    this the update script
    <?php
    
    mysql_connect("localhost", "root", "") or die(mysql_error()) ;
    mysql_select_db("upload") or die(mysql_error()) ;
    
    
    $id=$_POST['id'];
    $myfile=$_POST['myfile'];
    $name = $_FILES['name'];
    
    
    $query="UPDATE image SET myfile='$myfile', name='$name' WHERE id='$id'";
    mysql_query($query);
    echo "Record Updated";
    mysql_close();
    ?>
    PHP:
    and this is the upload file script
    <?php
    mysql_connect("localhost", "root", "") or die(mysql_error()) ;
    mysql_select_db("upload") or die(mysql_error()) ;
    
    // my file the name of the input area on the form type is the extension of the file
    //echo $_FILES["myfile"]["type"];
    
    //myfile is the name of the input area on the form 
    $name = $_FILES["myfile"] ["name"]; // name of the file
    $type = $_FILES["myfile"]["type"]; //type of the file
    $size = $_FILES["myfile"]["size"]; //the size of the file
    $temp = $_FILES["myfile"]["tmp_name"];//temporary file location when click upload it temporary stores on the computer and gives it a temporary name
    $error =array(); // this an empty array where you can then call on all of the error messages
    $allowed_exts = array('jpg', 'jpeg', 'png', 'gif'); // array with the following extension name values
    $image_type = array('image/jpg', 'image/jpeg', 'image/png', 'image/gif'); // array with the following image type values
    $location = 'images/'; //location of the file or directory where the file will be stored
    $appendic_name = "news".$name;//this append the word [news] before the name so the image would be news[nameofimage].gif
    
    // substr counts the number of carachters and then you the specify how how many you letters you want to cut off from the beginning of the word example drivers.jpg it would cut off dri, and would display vers.jpg
    //echo $extension = substr($name, 3);
    
    //using both substr and strpos, strpos it will delete anything before the dot in this case it finds the dot on the $name file deletes and + 1 says read after the last letter you delete because you want to display the letters after the dot. if remove the +1 it will display .gif which what we want is just gif
    $extension = strtolower(substr($name, strpos ($name, '.') +1));//strlower turn the extension non capital in case extension is capital example JPG will strtolower will make jpg
    // another way of doing is with explode
    // $image_ext strtolower(end(explode('.',$name))); will explode from where you want in this case from the dot adn end will display from the end after the explode
    
    $myfile = $_POST["myfile"];
    
         if (isset($name)) // if you choose a file name do the if bellow
           {
           
           // if extension is not equal to any of the variables in the array $allowed_exts error appears
            if(in_array($extension, $allowed_exts) === false )
           {
             $error[] = 'Extension not allowed! gif, jpg, jpeg, png only<br />'; // if no errror read next if line
           }
            // if file type is not equal to any of the variables in array $image_type error appears
            if(in_array($type, $image_type) === false)
           {
              $error[] = 'Type of file not allowed! only images allowed<br />';     
           }
           
            // if file bigger than the number bellow error message
            if($size > 2097152)
           {
              $error[] = 'File size must be under 2MB!';     
           }
           
           // check if  folder exist in the server
            if(!file_exists ($location))
           {
              $error[] = 'No directory ' . $location. ' on the server Please create a folder ' .$location;     
           }
                
         }
         // if no error found do the move upload function
           if (empty($error)){
               if (move_uploaded_file($temp, $location .$appendic_name))
               {
                 // insert data into database first are the field name teh values are the variables you want to insert into those fields appendic is the new name of the image
    mysql_query("INSERT INTO image (myfile ,name)
     VALUES ('$myfile', '$appendic_name')") ;
               exit();
               }
             }
           else
              {
            foreach ($error as $error)
               {
                   echo $error;
               }
            }
          
         
      
    //echo $type;
    ?>
    PHP:
    Thanks in advance
     
    macaela, Oct 1, 2011 IP
  2. HuggyEssex

    HuggyEssex Member

    Messages:
    297
    Likes Received:
    4
    Best Answers:
    2
    Trophy Points:
    45
    #2
    I think you should change this part:
    
    $myfile = $_POST["myfile"];
    
    PHP:
    to
    
    $myfile = $name;
    
    PHP:
    Just to note you do need to check that the file does not already exists on the server, you do this by using the is_file() function.

    Glen
     
    HuggyEssex, Oct 2, 2011 IP
  3. macaela

    macaela Active Member

    Messages:
    181
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    51
    #3
    Hi i don't quite understand how is that line will produce results sorry i am just a newbie but i think from that line bellow it means
    $myfile = $name;
    PHP:
    those two are rows in my database field $myfile and field $name in that database and you saying that field $myfile to be equal to field $name
    so in the database will be
     
    macaela, Oct 2, 2011 IP
  4. macaela

    macaela Active Member

    Messages:
    181
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    51
    #4
    Ok i managed to get to update just one problem it only updates the database if an image is upload if no image uploaded it doesnt update the database. is there a way i can set if no image upload just update the rest of the fields else update whatver else need updating?
    mysql_query("UPDATE image SET myfile='$myfile', image='$appendic_name' WHERE id=$id");  
    PHP:
     
    macaela, Oct 2, 2011 IP
  5. macaela

    macaela Active Member

    Messages:
    181
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    51
    #5
    Ok i think i'm almost there the problem now is if no image is uploaded it updates the database to null because no image has been entered is there a way that i can do if no image enter keep details of old image this what i've done for the rest of the update to work
    mysql_query("UPDATE image SET myfile='$myfile', image='$appendic_name' WHERE id=$id");
         if (isset($image)) // if you choose a file name do the if bellow
           {
    PHP:
     
    macaela, Oct 2, 2011 IP
  6. macaela

    macaela Active Member

    Messages:
    181
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    51
    #6
    Ok i managed to get it the update script to work just one thing i am a bit concern about i had to add two update set line on the script so not sure if that is correct thing to do, the reason i had to do that is because i have a upload restriction which include if file empty appear error message and dont run the script for security reason. but because user might just modify the text fields the script wont run cz the image field will be empty. so i had to include an update for the fields also outside those image restriction. my question is is this valid way of doing or could be a more effiecient way.
    here the whole script first update line is is just before the ( if (isset($image))) and then after that and all the image check is the second update is that reliable way of doing it???
    
    <?php
    /* this is a normal update without image as a start example 
    mysql_connect("localhost", "root", "") or die(mysql_error()) ;
    mysql_select_db("upload") or die(mysql_error()) ;
    
    
    $id=$_POST['id'];
    $myfile=$_POST['myfile'];
    $name = $_FILES['name'];
    
    
    $query="UPDATE image SET myfile='$myfile', name='$name' WHERE id='$id'";
    mysql_query($query);
    echo "Record Updated";
    mysql_close();
    */
    ?>
    
    <?php
    mysql_connect("localhost", "root", "") or die(mysql_error()) ;
    mysql_select_db("upload") or die(mysql_error()) ;
    
    // my file the name of the input area on the form type is the extension of the file
    //echo $_FILES["myfile"]["type"];
    
    //myfile is the name of the input area on the form 
    $name = $_FILES["image"]["name"]; // name of the file
    $type = $_FILES["image"]["type"]; //type of the file
    $size = $_FILES["image"]["size"]; //the size of the file
    $temp = $_FILES["image"]["tmp_name"];//temporary file location when click upload it temporary stores on the computer and gives it a temporary name
    $error =array(); // this an empty array where you can then call on all of the error messages
    $allowed_exts = array('jpg', 'jpeg', 'png', 'gif'); // array with the following extension name values
    $image_type = array('image/jpg', 'image/jpeg', 'image/png', 'image/gif'); // array with the following image type values
    $location = 'images/'; //location of the file or directory where the file will be stored
    $appendic_name = "news".$name;//this append the word [news] before the name so the image would be news[nameofimage].gif
    
    // substr counts the number of carachters and then you the specify how how many you letters you want to cut off from the beginning of the word example drivers.jpg it would cut off dri, and would display vers.jpg
    //echo $extension = substr($name, 3);
    
    //using both substr and strpos, strpos it will delete anything before the dot in this case it finds the dot on the $name file deletes and + 1 says read after the last letter you delete because you want to display the letters after the dot. if remove the +1 it will display .gif which what we want is just gif
    $extension = strtolower(substr($name, strpos ($name, '.') +1));//strlower turn the extension non capital in case extension is capital example JPG will strtolower will make jpg
    // another way of doing is with explode
    // $image_ext strtolower(end(explode('.',$name))); will explode from where you want in this case from the dot adn end will display from the end after the explode
    
    $id = $_POST["id"];
    $myfile = $_POST["myfile"];
    $image = $_FILES['image'];	
    mysql_query("UPDATE image SET myfile='$myfile' WHERE id=$id"); // update here otherwise if no image wont update the rest of the fields
         if (isset($image)) // if you choose a file name do the if bellow
           {
       	   	    
    		// if extension is not equal to any of the variables in the array $allowed_exts error appears
            if(in_array($extension, $allowed_exts) === false )
           {
             $error[] = 'Extension not allowed! gif, jpg, jpeg, png only<br />'; // if no errror read next if line
           }
            // if file type is not equal to any of the variables in array $image_type error appears
            if(in_array($type, $image_type) === false)
           {
              $error[] = 'Type of file not allowed! only images allowed<br />';     
           }
           
            // if file bigger than the number bellow error message
            if($size > 2097152)
           {
              $error[] = 'File size must be under 2MB!';     
           }
           
           // check if  folder exist in the server
            if(!file_exists ($location))
           {
              $error[] = 'No directory ' . $location. ' on the server Please create a folder ' .$location;     
           }
                
         }
         // if no error found do the move upload function
           if (empty($error)){
               if (move_uploaded_file($temp, $location .$appendic_name))
               {
                 // update data into database first are the field name teh values are the variables you want to insert into those fields appendic is the new name of the image
    			 $sql = "SELECT image
                  FROM image
                  WHERE id = $id";
    
          $result = mysql_query($sql) 
                    or die('Error, get details info failed. ' . 
                            mysql_error());
          $row = mysql_fetch_assoc($result);
          unlink($location . $row['image']);
    
       } else {
          // don't change the image
    	  $appendic_name = "image";
       }
    
       $query = "UPDATE image 
                   SET myfile  = '$myfile', 
                     image = '$appendic_name'
                 WHERE id = $id";
    
       mysql_query($query) 
      	 or die('Error, modify details failed : ' . mysql_error());
               }
           
           else
              {
            foreach ($error as $error)
               {
                   echo $error;
               }
            }
    
    ?>
    
    PHP:
     
    macaela, Oct 2, 2011 IP
  7. macaela

    macaela Active Member

    Messages:
    181
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    51
    #7
    Hi i've fixed the problem so just posting here in case anyone ever needed and in case someone spot something not right on the script but so far working 100% thanks for all the helps
    <?php
    mysql_connect("localhost", "root", "") or die(mysql_error()) ;
    mysql_select_db("your_database_name") or die(mysql_error()) ;
    
    // my file the name of the input area on the form type is the extension of the file
    //echo $_FILES["myfile"]["type"];
    
    //myfile is the name of the input area on the form 
    
    $name = $_FILES["image"]["name"]; // name of the file
    $type = $_FILES["image"]["type"]; //type of the file
    $size = $_FILES["image"]["size"]; //the size of the file
    $temp = $_FILES["image"]["tmp_name"];//temporary file location when click upload it temporary stores on the computer and gives it a temporary name
    $error =array(); // this an empty array where you can then call on all of the error messages
    $allowed_exts = array('jpg', 'jpeg', 'png', 'gif'); // array with the following extension name values
    $image_type = array('image/jpg', 'image/jpeg', 'image/png', 'image/gif'); // array with the following image type values
    $location = 'images/'; //location of the file or directory where the file will be stored
    $appendic_name = "news".$name;//this append the word [news] before the name so the image would be news[nameofimage].gif
    
    // substr counts the number of carachters and then you the specify how how many you letters you want to cut off from the beginning of the word example drivers.jpg it would cut off dri, and would display vers.jpg
    //echo $extension = substr($name, 3);
    
    //using both substr and strpos, strpos it will delete anything before the dot in this case it finds the dot on the $name file deletes and + 1 says read after the last letter you delete because you want to display the letters after the dot. if remove the +1 it will display .gif which what we want is just gif
    $extension = strtolower(substr($name, strpos ($name, '.') +1));//strlower turn the extension non capital in case extension is capital example JPG will strtolower will make jpg
    // another way of doing is with explode
    // $image_ext strtolower(end(explode('.',$name))); will explode from where you want in this case from the dot adn end will display from the end after the explode
    
    $id = $_POST["id"];
    $myfile = $_POST["myfile"];
    $image = $_FILES['image'];
    
    if($name=="") // if name is empty just update these fields on the database
    {	
         $query = "UPDATE upload 
                   SET myfile  = '$myfile'
                 WHERE id = '$id'";
    
       mysql_query($query) 
      	 or die('Error, modify details failed : ' . mysql_error());	
    }
    else // if image has name execute these lines
    {
       	   	    
    		// if extension is not equal to any of the variables in the array $allowed_exts error appears
            if(in_array($extension, $allowed_exts) === false )
           {
             $error[] = 'Extension not allowed! gif, jpg, jpeg, png only<br />'; // if no errror read next if line
           }
            // if file type is not equal to any of the variables in array $image_type error appears
            if(in_array($type, $image_type) === false)
           {
              $error[] = 'Type of file not allowed! only images allowed<br />';     
           }
           
            // if file bigger than the number bellow error message
            if($size > 2097152)
           {
              $error[] = 'File size must be under 2MB!';     
           }
           
           // check if  folder exist in the server
            if(!file_exists ($location))
           {
              $error[] = 'No directory ' . $location. ' on the server Please create a folder ' .$location;     
           }            
         // if no error found do the move upload function
           if (empty($error)){
               move_uploaded_file($temp, $location .$appendic_name);
               
                 // update data into database first are the field name teh values are the variables you want to insert into those fields appendic is the new name of the image
    			 $sql = "SELECT image
                  FROM upload
                  WHERE id = '$id'";
    
          $result = mysql_query($sql) 
                    or die('Error, get details info failed. ' . 
                            mysql_error());
          $row = mysql_fetch_assoc($result);
          unlink($location . $row['image']);//remove the image from the folder remmebr $location is 
         $query = "UPDATE upload 
                   SET myfile  = '$myfile', 
                     image = '$appendic_name'
                 WHERE id = '$id'";
    
       mysql_query($query) 
      	 or die('Error, modify details failed : ' . mysql_error());
               }
    	   
           else
              {
            foreach ($error as $error)
               {
                   echo $error;
               }
    		  }
    }
    
    //echo $type;
    ?>
    PHP:
     
    macaela, Oct 3, 2011 IP