简体   繁体   中英

How to upload image and save path to database?

I have a page where some images are shown (database driven). Here is the code of my gallery.php :

<ul id="portfolio-list" class="gallery">
    <?php
        $sql="select * from eikones ";
        $res=mysql_query($sql);
        $count=mysql_num_rows($res);

        for ( $i = 0; $i < $count; ++$i )
        {
            $row = mysql_fetch_array( $res );
            $co=$i+1;
            if(isset($row[ "path" ]))
            {
                $path= $row[ "path" ];
            }

            if(isset($row[ "auxon" ]))
            {
                $auxon = $row[ "auxon" ];
            }


            if($_SESSION['role'] == "admin")
                echo "<li class=\"pink\"><a href=\"$path\" rel=\"group1\" class=\"fancybox\" title=\"Προιόν \"><img src=\"$path\" alt=\"Pic\"></a></li>\n";

        }

        ?>


</ul>

Now I want to have a form where I will be able to upload an image. I am trying this but it doesn't work :

<form enctype="multipart/form-data" action="gallery.php" method="post" name="changer">
<input name="image" accept="image/jpeg" type="file">
<input value="Submit" type="submit">
</form>

<?php

include 'conf.php'; //database connect

if (isset($_FILES['image']) && $_FILES['image']['size'] > 0) { 


  $tmpName  = $_FILES['image']['tmp_name'];  


  $fp      = fopen($tmpName, 'r');
  $data = fread($fp, filesize($tmpName));
  $data = addslashes($data);
  fclose($fp);


  $query = "INSERT INTO eikones"; //table name = "eikones" and it has two columns named "auxon" and "path". The auxon is the id.
  $query .= "(image) VALUES ('','$data')";
  $results = mysql_query($query, $link) or die(mysql_error());

  print "DONE";

  }
  else {
  print "NO IMAGE SELECTED";
  }

?>

It says "NO IMAGE SELECTED" and nothing new comes into the database.

After some hours I found a solution. It works. Although I would still be happy to find a second solution (according to the code I first posted here). Here is the second solution :

form page :

<form enctype="multipart/form-data" action="insert_image.php" method="post" name="changer">
<input name="image" accept="image/jpeg" type="file">
<input value="Submit" type="submit">
</form>

insert to database page :

<?php

  include 'conf.php';

  if ($_FILES["image"]["error"] > 0)
  {
     echo "<font size = '5'><font color=\"#e31919\">Error: NO CHOSEN FILE <br />";
     echo"<p><font size = '5'><font color=\"#e31919\">INSERT TO DATABASE FAILED";
   }
   else
   {
     move_uploaded_file($_FILES["image"]["tmp_name"],"images/" . $_FILES["image"]["name"]);
     echo"<font size = '5'><font color=\"#0CF44A\">SAVED<br>";

     $file="images/".$_FILES["image"]["name"];
     $sql="INSERT INTO eikones (auxon, path) VALUES ('','$file')";

     if (!mysql_query($sql))
     {
        die('Error: ' . mysql_error());
     }
     echo "<font size = '5'><font color=\"#0CF44A\">SAVED TO DATABASE";

   }

   mysql_close();

?>

There are plenty of small classes you can download to handle your image uploads. Here's something small I just coded up. It will allow you to set validation for file type and file size. Feel free to make some methods private or hardcode the protected variables in the constructor if you know they'll always be the same. It may need a little work, but you can either use this class or pull out the bits you need to do it procedurally. Forgive any minor errors.

class ImageUploader{

    protected
        $size_limit,
        $allowed_extensions;
        $failed_saves;

    public function __construct(int $limit, array $extensions){
        $this->size_limit = $limit;
        $allowed_extensions = $extensions;
    }

    public function saveImage(array $images){
        foreach($images as $image){
            if($this->meetsSizeLimit($image['size'])){
                if($this->hasValidExtension(end(explode(".", $image["name"])))){
                    $this->storeImage($image, $this->getNextImageIndex());
                }
                else    $failed_saves[$image["name"] = "Invalid file type.";
            }
            else    $failed_saves["name"] = "File is too large.";
        }
        return $failed_saves;
    }

    public function meetsSizeLimit(int $size){
        return $size <= $this->size_limit;
    }

    public function hasValidExtension(string $extention){
        return in_array($extension, $this->allowed_extensions)
    }

    public function storeImage($image, $unique_id){
        move_uploaded_file($image["tmp_name"], "you_relative_file_path" . $image["name"]);
        rename('your_relative_file_path' . $image["name"], 'your_relative_file_path/img' . $unique_id . '.' . $extension);
        //Place your query for storing the image id and path in table 'eikones'
    }

    public function getNextImageIndex(){
        //Code to get the next available image id or MAX(id) from table 'eikones'
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM