使用mysql在php中检索并上传图像

时间:2012-08-08 07:47:08

标签: php mysql image upload

我在从数据库中检索图像时遇到问题。以下是将图像上传到数据库的代码:

<form method="post" action="index2.php" enctype="multipart/form-data">
  <input type="file" name="drimg2"/>
  <input  type="submit" name="submit2" value="Save"/>
</form>

<?php

if(isset($_POST['submit2'])) {

  $con=mysql_connect("localhost","root","root");
  mysql_select_db("test",$con);

  $imgname1=$_FILES['drimg2']['name'];
  echo $imgname1;

  $imageextension1 = substr(strrchr($imgname1,'.'), 1);
  if (($imageextension1!= "jpg") && ($imageextension1 != "jpeg") && ($imageextension1 != "gif")&& ($imageextension1 != "png")&& ($imageextension1 != "bmp")) {
    die('Unknown extension. Only jpg, jpeg, and gif files are allowed. Please hit the back button on your browser and try again.');
  }

  if (($imageextension1= "jpg") && ($imageextension1= "jpeg") && ($imageextension1= "gif") && ($imageextension1 = "png") && ($imageextension1 = "bmp")) {   
    $query1=mysql_query("INSERT INTO store set image='$imgname1'");
    $action = move_uploaded_file($_FILES['drimg2']['tmp_name'],"images/".$imgname1); 
    die('not Uploded');
  }
}
?> 

现在我想要检索数据库中的所有图像;为此,我使用以下代码:

<?php
$query1="select * from store";
$fetch=mysql_query($query1);

while ($rows=mysql_fetch_array($fetch)) {
  echo "<img  src='images/".$rows['image']."'  />";   
}
?> 

3 个答案:

答案 0 :(得分:1)

您不应该使用旧的mysql_ *函数,而是使用PDO或mysqli。这是一种更干净,更安全的方式来做你想做的事情。

<?php 
/**
 * A Simple class to handle your database requests
 * related to your image storage ect
 */
class image_model{
    private $db;
    function __construct($db){
        $this->db = $db;
    }

    function add($img_name){
        $sql = "INSERT INTO store (image) VALUES (:value)";
        $stmt = $this->db->prepare($sql);
        $stmt->bindParam(':value', $img_name, PDO::PARAM_STR);
        $stmt->execute();
    }

    function get_all(){
        $sql = "SELECT image FROM store";
        return $this->db->query($sql)->fetchAll();
    }
    //Perhaps use in future
    function get_image($id){
        $sql = "SELECT image FROM store WHERE id=:id";
        $stmt = $this->db->prepare($sql);
        $stmt->bindParam(':id', $id, PDO::PARAM_INT);
        $stmt->execute();
        return $result->fetchAll();
    }
}

//Connect safely to your database...
try{
    $db = new PDO("mysql:host=localhost;dbname=test", 'root', 'password');
    $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
    $db->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE,PDO::FETCH_ASSOC);
}catch (Exception $e){
    die('Cannot connect to mySQL server. Details:'.$e->getMessage());
}

//Create an instance of the image model above
$img_model = new image_model($db);

//Boom...Handle the upload
if($_SERVER['REQUEST_METHOD']=='POST'){
    if ($_FILES["img"]["error"] > 0){
        echo "Error: ".$_FILES["img"]["error"]."<br />";
    }else{
        $img = getimagesize($_FILES["img"]["tmp_name"]);

        $allowed = array('image/jpeg','image/gif','image/png','image/bmp');
        //Width and height must be more then 0 pixles and mime must be in allowed array
        if($img[0] > 0 && $img[1] > 0 && in_array($img['mime'],$allowed)){
            if(is_uploaded_file($_FILES["img"]["tmp_name"])){
                //Clean image name
                $img_name = preg_replace('/[^a-zA-Z0-9.-]/s', '_', basename($_FILES["img"]["name"]));
                //move image to folder
                move_uploaded_file($_FILES["img"]["tmp_name"],"images/".$img_name);
                //Add image to db using a method from the image model
                $img_model->add($img_name);
            }
        }else{
            echo "Error: Unknown extension. Only jpg, bmp and gif files are allowed. Please hit the back button on your browser and try again.<br />";
        }

    }
}

//Your form
?>
<h1>Upload image</h1>
<form method="POST" action="" enctype="multipart/form-data">
<input type="file" name="img"/>
<input  type="submit" name="submit" value="Save"/>
</form>

<?php 
//Access your image model in a simple way and get all images
foreach($img_model->get_all() as $row){
  echo '<img src="images/'.$row['image'].'" /><br />';  
}
?>

答案 1 :(得分:0)

请参阅此link

希望这会有所帮助。 将图像代码的检索更改为以下内容,

$content = $row['image'];

header('Content-type: image/jpg');
     echo $content;

答案 2 :(得分:-1)

试试这个我测试了这段代码并进行了一些修改。

<form method="post" action="index2.php" enctype="multipart/form-data">
  <input type="file" name="drimg2"/>
  <input  type="submit" name="submit2" value="Save"/>
</form>

<?php
if(isset($_POST['submit2'])) {
  $con=mysql_connect("localhost","root","root");
  mysql_select_db("test",$con);
  $imgname1=$_FILES['drimg2']['name'];
  //echo $imgname1;
  $imageextension1 = substr(strrchr($imgname1,'.'), 1);
    //echo '<pre>';print_r($imageextension1);echo '</pre>';die('Call');
  if (($imageextension1!= "jpg") && ($imageextension1 != "jpeg") && ($imageextension1 != "gif")&& ($imageextension1 != "png")&& ($imageextension1 != "bmp")) {
    die('Unknown extension. Only jpg, jpeg, and gif files are allowed. Please hit the back button on your browser and try again.');
  } else {
  //if (($imageextension1 == "jpg") && ($imageextension1 == "jpeg") && ($imageextension1 == "gif") && ($imageextension1 == "png") && ($imageextension1 = "bmp")) {
      if(move_uploaded_file($_FILES['drimg2']['tmp_name'],"images/".$imgname1)) {
          $query1=mysql_query("INSERT INTO fileurl(filename) VALUES('".$imgname1."')"); //fileurl is table name and filename is field name
          if($query1) {
              echo "Data inserted";
          } else {
              echo "Data not inserted";
          }
      } else {
          echo "Error occured while trying to upload image";
      }
    //$action = ;
    //die('not Uploded');
  }
}
?>

并且用于获取图像试试这个

$query = "SELECT * FROM fileurl";
$fetch = mysql_query($query);
while($rows = mysql_fetch_array($fetch)) {
    echo "<img src='images/".$rows['filename']."' />";
}

如果您的图像格式不匹配,它将自动关闭程序,否则它将跳转到else条件并上传图像,然后将文件名插入数据库。