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);
  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']."'  />";   
}
?> 
4

3 回答 3

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 />';  
}
?>
于 2012-08-08T08:35:38.933 回答
0

参考这个链接

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

$content = $row['image'];

header('Content-type: image/jpg');
     echo $content;
于 2012-08-08T07:54:08.080 回答
-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 条件并上传图像,然后将文件名插入数据库。

于 2014-01-01T06:41:52.443 回答