Why is my image not uploading?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • tdrsam
    New Member
    • May 2015
    • 97

    Why is my image not uploading?

    I have a from that brings a record from the database, including the image that is currently stored for that record. The user can then update the information for the record, but the problem is that when I pass the new image from the php page with the form to the script that processes the update of the database record, the image is not actually passing.

    This is the php that brings the record from the database to the page:

    Code:
    <?php
    include ('includes/DbCon.php');
    $id = intval($_GET['id']);
    $target_dir = $_SERVER['DOCUMENT_ROOT'].'/pc.v.2/images/photo/';
    $query = "SELECT * FROM news WHERE id = '$id'";
    $result = $mysqli->query ($query);
    if(mysqli_num_rows($result)>=1){
    $row = mysqli_fetch_array($result, MYSQLI_BOTH);
    $headline = $row['headline'];
    $body = $row['body'];
    $image = $row['image'];
    }
    ?>
    This is the form to display the record:

    Code:
    <form action="update.php" method="post" class="newNews">
    <input type="hidden" name="ud_id" value="<?=$id;?>">
    <!-- <input type="hidden" name="old_id" value="<?=$image;?>"> -->
    
    <label for="title">Title</label><br />
    <input type="text" name="ud_headline" value="<?=$headline;?>"/><br /><br /><br />
    
    <label for="text">Body</label><br />
    <textarea name="ud_body" rows="5" cols="21" value="" class="editBody"><?=$body;?></textarea><br />
    
    <p>Current Photo</p>
    <img src="images/photo/<?=$image?>" alt=" " width="auto" height="auto"><br /> <!-- $target_dir. -->
    
    <input type="file" name="ud_image" class="newsImage" ><br />
    <input type="submit" name="submit" value="Update news item" class='addNew' />
    </form>
    And this is the update.php file that processes the update:

    Code:
    <?php
    include ('includes/DbCon.php');
    $target_dir = 'images/photo/'; // $_SERVER['DOCUMENT_ROOT'].'/pc.v.2/
    $target_file = $target_dir . basename($_FILES["ud_image"]["name"]);
    if (move_uploaded_file($_FILES["ud_image"]["tmp_name"], $target_file))
    {
    echo '<script type="text/javascript">';
    echo 'alert("News Items Saved")';
    echo '</script>';
    }
    else {
    echo "Sorry, there was an error with your file.";
    }
    if (isset($_POST['id']))$ud_id = $_POST['id'];
    if (isset($_POST['ud_headline']))$ud_headline = $_POST['ud_headline'];
    if (isset($_POST['ud_body']))$ud_body = $_POST['ud_body'];
    if (isset($_POST['ud_image']))$ud_image = $_POST['ud_image'];
    if(isset($_POST['submit'])){
    	$query = "UPDATE news SET headline='$ud_headline', body='$ud_body', 
    	image='$ud_image' WHERE id='$ud_id'";
    	if($mysqli->affected_rows>=1){
    	//$result = $mysqli->query($query);  .$_FILES[ud_image][name]
    	echo '<script type="text/javascript">';
    	echo 'document.location.href = "/pc.v.2/admin-news.php";';
    	echo '</script>';
    	}
    	else
    	{
    	echo '<script type="text/javascript">';
    	echo 'alert("The news item was not able to be created. Please try again."). mysql_error()';
    	echo '</script>';
    	}}
    	
    $mysqli->close();
    ?>
    Why is the image not passing from the form to the script?
  • computerfox
    Contributor
    • Mar 2010
    • 276

    #2
    You're using $_POST['ud_image'], but isn't it suppose to be a $_FILE?
    If this is an update, I would actually start the code by initializing the values with the current values, then when the submit button gets hit, gather the new values and check if the file is set, if not, use the current value, if it is set, use the uploaded value.

    Hope that helps.

    Comment

    • tdrsam
      New Member
      • May 2015
      • 97

      #3
      Ok, so I've changed my update.php script, the one that processes the update of the db record. This is what I have:

      Code:
      <?php
      include ('includes/DbCon.php');
      
      // Initialize the current values.
      $query = "SELECT * FROM news WHERE id = '$id'";
      $result = $mysqli->query ($query);//or die(mysqli_error($result->db_link));;
      if(mysqli_num_rows($result)>=1)
      {
      $row = mysqli_fetch_array($result, MYSQLI_BOTH);
      	$headline = $row['headline'];
      	$body = $row['body'];
      	$image = $row['image'];
      }
      else{
          $mysqli->error;
      }
      
      // When submit button gets hit
      if(isset($_POST['submit'])){
      
      // Gather the new values
      if (isset($_POST['id']))$ud_id = $_POST['id'];
      if (isset($_POST['ud_headline']))$ud_headline = $_POST['ud_headline'];
      if (isset($_POST['ud_body']))$ud_body = $_POST['ud_body'];
      if (isset($_POST['ud_image']))$ud_image = $_POST['ud_image'];
      
      // Check if the file is set
      $target_dir = 'images/photo/'; // $_SERVER['DOCUMENT_ROOT'].'/pc.v.2/
      $target_file = $target_dir . basename($_FILES["ud_image"]["name"]);
      if (!move_uploaded_file($_FILES["ud_image"]["tmp_name"], $target_file))
      {
      
      // If not use the current value
      $query2 = "UPDATE news SET headline='$ud_headline', body='$ud_body', 
      image='$image' WHERE id='$ud_id'";
      $result2 = $mysqli->query($query2)or$mysqli->error;
      }							
      else
      {
      
      // If isset, use the new value
      $query3 = "UPDATE news SET headline='$ud_headline', body='$ud_body', 
      image='$ud_image' WHERE id='$ud_id'";
      $result3 = $mysqli->query($query3)or$mysqli->error;
      }
      }
      else
      {
      $mysqli->error;
      }
      echo '<script type="text/javascript">';
      echo 'location.replace.href="/pc.v.2/news.php")';
      echo '</script>';
      $mysqli->close();
      ?>
      But, unsurprisingly it's not working. I might need some help with this one as it's slightly towards the advanced side for my level of experience.

      Comment

      • tdrsam
        New Member
        • May 2015
        • 97

        #4
        "You're using $_POST['ud_image'], but isn't it suppose to be a $_FILE?"

        I use the post with 'image' in the create section of this system and it works, so I assume it would work for the update as well. Is that not necessarily true?

        Comment

        • computerfox
          Contributor
          • Mar 2010
          • 276

          #5
          As for the update code (this isn't a script by the way), simply take the code from the create part and modify it to use update... where heading='$headi ng' .

          First off where are you setting the value for the id here? The only thing I see is where you're trying to grab the data for something that isn't set. You should pass the identifier value to the URL and retrieve the ID by using $_GET['id'].

          Normally, you use $_FILE if you're using a file input type. POST just isn't standard and might not always work.

          Comment

          • tdrsam
            New Member
            • May 2015
            • 97

            #6
            I'll try modifying the insert statement and see if that works.

            Funny you say that the value for the id isn't set. I noticed that this morning too. So, I used a var_dump to see what I was getting and fixed the code until it showed I was bringing the right id across.

            I'll try again now.

            Comment

            • computerfox
              Contributor
              • Mar 2010
              • 276

              #7
              Ehhhh.... for this query, it'll be something like update news set.... where id='$id'

              Comment

              • tdrsam
                New Member
                • May 2015
                • 97

                #8
                Yeah, I can't even get that far now. I've tried making it so that the id is brought over first and that's working . Then I'm basically using the same script as the insert, but it's not finding the file, which is the next part of the script. I've got it set to upload the file the same way as the insert script, but I get an error message saying bool false

                Comment

                • computerfox
                  Contributor
                  • Mar 2010
                  • 276

                  #9
                  Please provide the CODE that you have now.

                  PS:
                  Script: System script like Python, Perl, Batch, PowerShell, Bash (no interactivity)
                  GUI: User interactivity is possible in a graphical interface.

                  If you're not sure, you can use "code". Just trying to educate you for when you talk about the system you're building.

                  Comment

                  • tdrsam
                    New Member
                    • May 2015
                    • 97

                    #10
                    Thanks. Here's the start of the code:

                    Code:
                    include ('includes/DbCon.php');
                    if (isset($_POST['ud_id']))$id = $_POST['ud_id'];
                    	
                    //Set directory etc for image upload
                    $target_dir = "images/photo/";
                    $target_file = $target_dir . basename($_FILES["ud_image"]["name"]);
                    
                    if (move_uploaded_file($_FILES["ud_image"]["tmp_name"], $target_file))
                    {
                    echo '<script type="text/javascript">';
                    echo 'alert("News Items Saved")';
                    echo '</script>';
                    }
                    else{
                    echo "Sorry, there was an error with your file.";
                    }
                    Even that won't go.

                    Comment

                    • computerfox
                      Contributor
                      • Mar 2010
                      • 276

                      #11
                      I feel like I keep giving you the same code. Have you reviewed the reference guides I posted?
                      You can't keep depending on us to fix up a system YOU are trying to build. This is considered consulting work which in other cases you'd have to pay for. You also forgot to clean up the code. How are you navigating to the update page? Can I please see the hyperlink?

                      Code:
                      <?php
                       include ('includes/DbCon.php');
                       $id=$_GET['id']; //Pass the id as a paramater in the url   ....php?id=
                       $getter=mysql_query("select* from news where id='$id'");
                       $d=mysql_fetch_assoc($getter);
                       $image_path=$d['image'];
                       $target_dir = "http://bytes.com/images/photo/";
                       $target_file = $target_dir . basename($_FILES["ud_image"]["name"]);
                       if(move_uploaded_file($_FILES["ud_image"]["tmp_name"], $target_file)){
                        $image_path=$target_file;
                        $succ=mysql_query("update news set image='$image_path' where id='$id'");
                        if($succ){
                         ?><script>alert("Image updated...");</script><?php
                        }
                       }
                       else{
                        print "Sorry, there was an error with your file.";
                       }
                      ?>
                      References:


                      Last edited by computerfox; Jun 25 '15, 03:58 AM. Reason: Added references

                      Comment

                      • tdrsam
                        New Member
                        • May 2015
                        • 97

                        #12
                        I can understand your frustration. Trust me when I say that no one has been more frustrated by this than me.

                        I can now happily report that the whole system is up and running. The problem I had was that I hadn't set the enctype on the form that posted to the update page. So sorry to have caused you this frustration over such a little mistake.

                        Comment

                        • computerfox
                          Contributor
                          • Mar 2010
                          • 276

                          #13
                          Yup that would also be the cause. That part is on me since I didn't catch it either, but I'm glad now that we took care of the rest of the code and the system is now functional. Sorry for being so rough with you I just wanted to make sure you had an awesome product that you can be proud of to talk about.

                          Comment

                          Working...