How to fix "Notice: Undefined offset" while inserting uploaded images into db?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • tbebest
    New Member
    • Dec 2010
    • 10

    How to fix "Notice: Undefined offset" while inserting uploaded images into db?

    Hi , i have a form and it has A problem:
    i upload my 3 image and it uploaded in definded path but in insert in db filed there are empty:
    Notice: Undefined offset: 0 in C:\wamp\www
    Notice: Undefined offset: 1 in C:\wamp\www
    Notice: Undefined offset: 2 in C:\wamp\www
    i think scope of my Array variable : newsimg[] has a problem.
    Code:
    <div id="postedit" class="clearfix">
    <h2 class="ico_mug">ADD NEWS</h2>
    <form method="post" action="<?php echo $_SERVER['PHP_SELF'] ?>"
                 enctype="multipart/form-data">
    <div>
                <input id="post_title" type="text" size="30" tabindex="1" name="post_title"
                 value="Title" />
                </div>
    <div id="form_middle_cont" class="clearfix">
    <div class="left">
    <textarea id="markItUp" cols="80" rows="10" tabindex="2" name="markItUp"></textarea>
                </div>
    <div class="left form_sidebar">
    <h3>Is A Member?</h3>
    <ul>
    <li>
    <label><input type="checkbox" class="noborder" name="chbox"  />Yes</label></li>
    </ul><BR/>
         <ul>
              <h4>News Pictures:</h4>
              <li><input type=file name="file[]" size=20 
                    accept="image/jpg,image/jpeg,image/png">
              </li>
              <li><input type=file name="file[]" size=20 
                    accept="image/jpg,image/jpeg,image/png">
              </li>
              <li><input type=file name="file[]" size=20 
                    accept="image/jpg,image/jpeg,image/png">
              </li>
              </ul>
    <p>
    <input type="hidden" name="MAX_FILE_SIZE" value="2097152" />
    <input type="submit" value="Store" id="save"  name="save"/>
    </p>
    
    </div>
                </div>
    
    </form>
    <?php
    if (isset($_POST['save'])) {
    
      $title = mysql_real_escape_string(trim($_POST["post_title"]));
      if ($title == '' || $title == 'Title'){
    
    die("
    <div id='fail' class='info_div'  align='center' dir='rtl'>
    <span class='ico_cancel'><strong>
    Insert Title,Please</strong></span><br />
    <a href=\"javascript: history.go(-1)\">Retry</a>
    </div>"); }
    $description = ( mysql_real_escape_string(trim($_POST["markItUp"])));
      if ($description == ''){
    die("
    <div id='fail' class='info_div'  align='center' dir='rtl'>
    <span class='ico_cancel'><strong>
    Insert News_body,Please</strong></span><br />
    <a href=\"javascript: history.go(-1)\">Retry</a>
    </div>"); }
      if (isset($_POST['chbox'])) $isprv = 'true';
    
      else  $isprv = 'false';
      //max fle size value
      $max_file_size = 2097152;
      //Global newsimg
      global $newsimg;global $ctr;
      //timestamp to make files unique names
      $timestamp = time();
      //destination folder path
      $destpath = "../Dir/Newsimg/";
      //looping each file or image from the form
      while(list($key,$value) = @each($_FILES["file"]["name"])) {
      //check if any empty or errors
      if(!empty($value)){
      if ($_FILES["file"]["error"][$key] > 0) {
      $edir ='<div id="fail" class="info_div">';
      $edir .='<span class="ico_cancel"><strong>';
      $edir .="ERR : ".  $_FILES["file"]["error"][$key]  .'</strong></span></div>';
      echo($edir);
      } else {
      //add the timestamp to filename
      $file_name = $timestamp.$_FILES['file']['name'];
      //temp name from upload form,  key of each is set
      $source = $_FILES["file"]["tmp_name"][$key] ;
      //getting the file type
      $file_type = $_FILES["file"]["type"][$key];
      //getting the file size
      $file_size = $_FILES["file"]["size"][$key];
      //getting the file width
      $file_width = GetImageSize($source);
      //placing each file name into a variable
      $filename1 = $_FILES["file"]["name"][$key];
      //lowering the file names
      $filename = strtolower($filename1);
      //adding timestamp to front of file name
      $filename = "$timestamp$filename";
      ++$timestamp;
      if ($file_type != "image/jpeg" && $file_type != "image/png" && $file_type != "image/jpg") {
    die("
    <div id='fail' class='info_div'>
    <span class='ico_cancel'><strong>
    Invalid Format</strong></span><br />
    <a href=\"javascript: history.go(-1)\">Retry</a>
    </div>"); }
    if($file_width[0] > 650) {
    die("
    <div id='fail' class='info_div'>
    <span class='ico_cancel'><strong>
    Width less than 650 Pixel!</strong></span><br />
    <a href=\"javascript: history.go(-1)\">Retry</a>
    </div>"); }
    if($file_size > 51200) {
    die("
    <div id='fail' class='info_div'>
    <span class='ico_cancel'><strong>
    Size less than 50KByte!</strong></span><br />
    <a href=\"javascript: history.go(-1)\">Retry</a>
    </div>"); }
     //moving the file to be saved from the temp location to the destination path
      move_uploaded_file($source, $destpath . $filename);
      //the actual final location with timestamped name
      $final_file_location = "$destpath$filename";
      //echo $final_file_location."<br />";
      if (file_exists($final_file_location)) {
      $newsimg[$ctr] = $filename;
      $ctr++;
    ?>
    <div id="success" class="info_div"><span class="ico_success"><strong>
    <a href="<?php echo $final_file_location; ?>" target="_blank"><?php echo $filename; ?></a>
    </strong></span></div><br />
    <?php
      }}}}
    $ctr=0;
    //Include database connection details
    require_once('../config.php');
    //Connect to mysql server
    $link = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);
    if(!$link) {
     die('Failed to connect to server: ' . mysql_error());
    }
    //Select database
    $db = mysql_select_db(DB_DATABASE);
    if(!$db) {
    die("Unable to select database");
     }
    
    $login = $_SESSION['SESS_LOG_IN'];
    
    $query = "INSERT INTO news SET postdate=NOW(),".
    
    "ttl='$title', newstxt='$description', ".
    
    "isprv='$isprv',authr='$login' ";
    
    if (isset($newsimg[0])) $query .=",newsimg1='$newsimg[0]'" ;
    
    if (isset($newsimg[1])) $query .=",newsimg2='$newsimg[1]'" ;
    
    if (isset($newsimg[2])) $query .=",newsimg3='$newsimg[2]'" ;
    
    if (mysql_query($query)) {
    echo '<div id="success" class="info_div">';
    echo'<span class="ico_success"><strong>';
    echo 'SuccessFul! </strong></span></div>';
    } else {
    echo'<div id="warning" class="info_div">';
    echo'<span class="ico_error"><strong>';
    echo "ERR in Insert NEWS : ".mysql_error()."</strong></span></div>";
    
    
    chdir('../Dir/Newsimg/'); 
    
    
    if (isset($newsimg[0])) unlink($newsimg[0]);
    
    if (isset($newsimg[1])) unlink($newsimg[1]);
    
    if (isset($newsimg[2])) unlink($newsimg[2]);
    
    }
    }
                ?> 
    
    	
    
    	
    
    </div><!-- end #postedit -->
  • code green
    Recognized Expert Top Contributor
    • Mar 2007
    • 1726

    #2
    I would say newsimg[] is empty.
    Output the contents to see if anything is in there

    Comment

    • tbebest
      New Member
      • Dec 2010
      • 10

      #3
      Hi, for my first value of array :if i use newsimg[] ,i have fatal error else i use newsimg[0] Notice: Undefined offset: 0; about other's i.e: newsimg[1] ,newsimg[2] ,the first sets good but the second doesn't set and if i don't set the first ,it places in newsimg[1];
      i think my way to use and point to values of array has a bug. TNX.

      Comment

      • code green
        Recognized Expert Top Contributor
        • Mar 2007
        • 1726

        #4
        Does that mean you have solved it?

        Comment

        • tbebest
          New Member
          • Dec 2010
          • 10

          #5
          Not completely, i have a problem with newsimg[0];
          my first value in array newsimg[0] in insert, is empty.
          Code:
           $query = "INSERT INTO news SET postdate=NOW(),".
           "ttl='$title', newstxt='$description', ".
           "isprv='$isprv',authr='$login' ";
           if (isset($newsimg[0])) $query .=",newsimg1='$newsimg[0]'" ;
           if (isset($newsimg[1])) $query .=",newsimg2='$newsimg[1]'" ;
           if (isset($newsimg[2])) $query .=",newsimg3='$newsimg[2]'" ;
           if (mysql_query($query)) {
          echo "<pre>";
          print_r($newsimg);
          echo "</pre>"; }
          Sample => Result:
          Array
          (
          [] => 1297148403tulip s 04.jpg
          [1] => 1297148404tulip s 03.jpg
          [2] => 1297148405tulip s 02.jpg
          )

          newsimg[0] doesn't store!

          Comment

          • code green
            Recognized Expert Top Contributor
            • Mar 2007
            • 1726

            #6
            You have not initialised $ctr.
            So the first time of
            Code:
            $newsimg[$ctr] = $filename;
            The index will be null.
            If you had error_reporting set (E_ALL | E_STRICT) then a 'Notice' level error would have been reported

            Comment

            • tbebest
              New Member
              • Dec 2010
              • 10

              #7
              Hi code green,Thanks for your attensions.

              Comment

              Working...