How to Keep image path name if no new image been uploaded?

Hi i have the following script which update and upload image to the folder and sends path to the database my issue is when editing the details
i have to keep sending a image otherwise the path to the image in the database updates empty is there away in my script that i can set if no new image upload keep old image path or dnt change the the row on database this my upload script?

//upload if the image is CHANGED		
 //set the uplopad location			
 $uploaddir = '../../../images_news/';				
 //THREE Possibilities now Follow..		
 // 1 - no image exists and there is no change		
 // 2 - an image exists and there is no change		
 // 3 - an image exists and there is a  change							
 // 1 - no image exists and there is no change			
 $current_image_name = $news_image;					
 // 2 - an image exists and there is no change			
 if( !($news_image=="") )
 {
  // $news_image is NOT empty				
  $uploadfile = $uploaddir . $news_image;				
  $current_image_name = $news_image;			
  }					
  if( !($file=="") )
  { // $file is NOT empty				
  $uploadfile = $uploaddir . $news_id . basename($_FILES['file']['name']);				
  $current_image_name = $news_id . basename($_FILES['file']['name']);			
  }					

  // 3 - if an image name DOES NOT exist, and a new file has been selected, then			 
  // $file is NOT empty				
 $target = '../../../images_news/';
 $target = $target . basename( $_FILES['file']['name']) ; 
 $file=$_FILES['file']['name'];
 $path=$target;	
 move_uploaded_file($_FILES['file']['tmp_name'],$path);

  // Strip those \\ / 			
  //str_replace("& amp ;", "&", (htmlentities(stripslashes($news_story), ENT_QUOTES)));		
  // All appears well, so enter into database					
$query= "UPDATE news SET
 news_title           = '$news_title',
 news_story	          = '$news_story',
 news_image	          = '$news_image',		
 news_image_caption	  = '$news_image_caption',
 news_image_link	  = '$news_image_link',
 news_date_day		  = '$news_date_day',
 news_date_month	  = '$news_date_month',
 news_date_year		  = '$news_date_year',
 news_status		  = '$news_status',
 news_website		  = '$news_website',
 news_date_modified	  = '$timestamp'
WHERE news_id='$news_id'";								

  $result = mysql_query($query) or die("could not execute query - Update CAMERAMEN Record to DB");		

wrap the whole thing in


if(isset($_FILES['file']['name'])) {

(if no file is uploaded, there wont be a name).

1 Like

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();
?>

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;
?>

Thanks in advance

In the 9th line down in the upload script you’ve go a space in

$name = $_FILES["myfile"] ["name"]; // name of the file

where there shouldn’t be one:

$name = $_FILES["myfile"]["name"]; // name of the file

Thanks but my issue is not quite the upload script cz that works fine with a simple upload form and will insert the data into the database my problem is i want to remove the insert part on the upload script and replace with an update script like the update above. i tried just to remove the insert into and add update but didnt work gives error
like replace.

mysql_query("INSERT INTO image (myfile ,name)
 VALUES ('$myfile', '$appendic_name')") ;

and put the update

$query="UPDATE image SET myfile='$myfile', name='$name' WHERE id='$id'";
mysql_query($query);
echo "Record Updated";

but gives me error in all of the these 4 lines

$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"];

Notice: Undefined index: myfile in C:\xampp\htdocs\upload_image\upload.php on line 12
Notice: Undefined index: myfile in C:\xampp\htdocs\upload_image\upload.php on line 13
Notice: Undefined index: myfile in C:\xampp\htdocs\upload_image\upload.php on line 14
Notice: Undefined index: myfile in C:\xampp\htdocs\upload_image\upload.php on line 15

which probably theres alot more into to make the upload into a update but i just dnt know what else to do

Your welcome but if you can help me turn that upload into an update i would really appreciate.

Add these lines at the end of the update script, they will tell you whether or not the update script is recieving anything from the script which is calling it:


var_dump($_POST);
var_dump($_FILES);

this what i get
array(3) { [“id”]=> string(2) “24” [“myfile”]=> string(12) “updatedagain” [“Submit”]=> string(6) “Submit” } array(1) { [“name”]=> array(5) { [“name”]=> string(10) “flying.jpg” [“type”]=> string(10) “image/jpeg” [“tmp_name”]=> string(24) “C:\xampp\ mp\php4AAF.tmp” [“error”]=> int(0) [“size”]=> int(10450) } }

In the update script, change this line:

$name = $_FILES['name'];

to

$name = $_FILES['name']['name'];

these are the error i got what i got

array(3) { ["id"]=> string(2) "24" ["myfile"]=> string(10) "my name is" ["Submit"]=> string(6) "Submit" } array(1) { ["name"]=> array(5) { ["name"]=> string(10) "flying.jpg" ["type"]=> string(10) "image/jpeg" ["tmp_name"]=> string(24) "C:\\xampp\	mp\\php692B.tmp" ["error"]=> int(0) ["size"]=> int(10450) } }
Notice: Undefined index: myfile in C:\\xampp\\htdocs\\upload_image\\upload.php on line 15

Notice: Undefined index: myfile in C:\\xampp\\htdocs\\upload_image\\upload.php on line 16

Notice: Undefined index: myfile in C:\\xampp\\htdocs\\upload_image\\upload.php on line 17

Notice: Undefined index: myfile in C:\\xampp\\htdocs\\upload_image\\upload.php on line 18

In each of lines 15-17 it is looking for (using line 15 as an example):

It is looking for

$_FILES["myfile"]["type"]["myfile"]

when what it’s looking for is found at:

$_FILES["name"]["type"]["myfile"]

you saying is looking for that

$_FILES["myfile"]["type"]["myfile"]  

but is only finding
this

$_FILES["name"]["type"]["myfile"] 

so all those for error i should replace with

$_FILES["name"]["type"]["myfile"] 

now myfile is a field name on my database which has the following fields
ID, MYFILE, NAME
id anytext image path

can you exaplain what you mean sorry?

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");

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, just need to keepbdetails of old image if image not modified??

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
       {

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;
           }
        }
	  
     
  
//echo $type;
?>


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;
?>