如何上传图像并保存到数据库的路径?

时间:2013-10-22 23:04:50

标签: php database image upload

我有一个显示某些图像的页面(数据库驱动)。这是我的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>

现在我想要一个可以上传图像的表单。我正在尝试这个,但它不起作用:

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

?>

它说“没有选择图像”,数据库中没有任何新内容。

2 个答案:

答案 0 :(得分:2)

几个小时后我找到了解决方案。有用。虽然我仍然乐意找到第二个解决方案(根据我在这里发布的代码)。这是第二个解决方案:

表单页面:

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

插入数据库页面:

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

?>

答案 1 :(得分:0)

您可以下载大量小班来处理图片上传。这是我编写的小东西。它允许您设置文件类型和文件大小的验证。如果您知道它们将始终相同,请随意将某些方法设为私有或对构造函数中的受保护变量进行硬编码。它可能需要一些工作,但你可以使用这个类或从程序上拉出你需要的位。原谅任何小错误。

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'
    }
}
相关问题