2014-11-05 156 views
5

如何在MySQL數據庫中存儲和顯示圖像。到現在我只寫的代碼是從用戶那裏得到的圖像,並將它們存儲在文件夾中,我寫到目前爲止是代碼: HTML文件如何使用php存儲圖像在mysql數據庫中

<input type="file" name="imageUpload" id="imageUpload"> 

PHP文件

$target_dir = "uploads/"; 
$target_file = $target_dir . basename($_FILES["imageUpload"]["name"]); 
$uploadOk = 1; 
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION); 


if (move_uploaded_file($_FILES["imageUpload"]["tmp_name"], $target_file)) { 
    echo "The file ". basename($_FILES["imageUpload"]["name"]). " has been uploaded."; 
} else { 
    echo "Sorry, there was an error uploading your file.";} 
+0

http://stackoverflow.com/questions/16382672/how-insert-and-retrieve-images-to-and-from-database-using-php – 2014-11-05 12:53:00

+4

我不會建議將圖像存儲在數據庫中,你目前做的是一種更好的方法。所有你需要做的是存儲數據庫中的圖像的路徑 – 2014-11-05 12:58:04

+0

感謝您的幫助,我想出了它。現在,我只是將上傳的文件的名稱存儲在我的數據庫中,然後檢索該名稱以便打開圖像,然後將其放在我想要的位置。 – 2014-11-05 13:25:52

回答

4

我找到了答案,對於那些正在尋找同樣的東西的人來說,我是這麼做的。 您不應該考慮將圖像上傳到數據庫,而是可以將上傳文件的名稱存儲在數據庫中,然後檢索文件名並在任何想要顯示圖像的地方使用。

HTML代碼

<input type="file" name="imageUpload" id="imageUpload"> 

PHP代碼

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

    //Process the image that is uploaded by the user 

    $target_dir = "uploads/"; 
    $target_file = $target_dir . basename($_FILES["imageUpload"]["name"]); 
    $uploadOk = 1; 
    $imageFileType = pathinfo($target_file,PATHINFO_EXTENSION); 

    if (move_uploaded_file($_FILES["imageUpload"]["tmp_name"], $target_file)) { 
     echo "The file ". basename($_FILES["imageUpload"]["name"]). " has been uploaded."; 
    } else { 
     echo "Sorry, there was an error uploading your file."; 
    } 

    $image=basename($_FILES["imageUpload"]["name"],".jpg"); // used to store the filename in a variable 

    //storind the data in your database 
    $query= "INSERT INTO items VALUES ('$id','$title','$description','$price','$value','$contact','$image')"; 
    mysql_query($query); 

    require('heading.php'); 
    echo "Your add has been submited, you will be redirected to your account page in 3 seconds...."; 
    header("Refresh:3; url=account.php", true, 303); 
} 

代碼來顯示圖像

while($row = mysql_fetch_row($result)) { 
    echo "<tr>"; 
    echo "<td><img src='uploads/$row[6].jpg' height='150px' width='300px'></td>"; 
    echo "</tr>\n"; 
} 
+1

用戶可能有上傳圖像到數據庫的正當理由,並且它可以是表達性的。它不是很受歡迎,所以也不如'支持'(即不那麼廣泛的知識庫) – Strawberry 2014-11-05 13:35:37

+5

警告:上述示例代碼對於SQL注入漏洞是敞開的。 – Clinton 2016-05-10 17:18:40

-1
<!-- 
//THIS PROGRAM WILL UPLOAD IMAGE AND WILL RETRIVE FROM DATABASE. UNSING BLOB 
(IF YOU HAVE ANY QUERY CONTACT:[email protected]) 


CREATE TABLE `images` (
    `id` int(100) NOT NULL AUTO_INCREMENT, 
    `name` varchar(100) NOT NULL, 
    `image` longblob NOT NULL, 
    PRIMARY KEY (`id`) 
) ENGINE=InnoDB ; 

--> 
<!-- this form is user to store images--> 
<form action="index.php" method="post" enctype="multipart/form-data"> 
Enter the Image Name:<input type="text" name="image_name" id="" /><br /> 

<input name="image" id="image" accept="image/JPEG" type="file"><br /><br /> 
<input type="submit" value="submit" name="submit" /> 
</form> 
<br /><br /> 
<!-- this form is user to display all the images--> 
<form action="index.php" method="post" enctype="multipart/form-data"> 
Retrive all the images: 
<input type="submit" value="submit" name="retrive" /> 
</form> 



<?php 
//THIS IS INDEX.PHP PAGE 
//connect to database.db name is images 
     mysql_connect("", "", "") OR DIE (mysql_error()); 
     mysql_select_db ("") OR DIE ("Unable to select db".mysql_error()); 
//to retrive send the page to another page 
if(isset($_POST['retrive'])) 
{ 
    header("location:search.php"); 

} 

//to upload 
if(isset($_POST['submit'])) 
{ 
if(isset($_FILES['image'])) { 
     $name=$_POST['image_name']; 
     $email=$_POST['mail']; 
     $fp=addslashes(file_get_contents($_FILES['image']['tmp_name'])); //will store the image to fp 
     } 
       // our sql query 
       $sql = "INSERT INTO images VALUES('null', '{$name}','{$fp}');"; 
          mysql_query($sql) or die("Error in Query insert: " . mysql_error()); 
} 
?> 



<?php 
//SEARCH.PHP PAGE 
    //connect to database.db name = images 
     mysql_connect("localhost", "root", "") OR DIE (mysql_error()); 
     mysql_select_db ("image") OR DIE ("Unable to select db".mysql_error()); 
//display all the image present in the database 

     $msg=""; 
     $sql="select * from images"; 
     if(mysql_query($sql)) 
     { 
      $res=mysql_query($sql); 
      while($row=mysql_fetch_array($res)) 
      { 
        $id=$row['id']; 
        $name=$row['name']; 
        $image=$row['image']; 

        $msg.= '<a href="search.php?id='.$id.'"><img src="data:image/jpeg;base64,'.base64_encode($row['image']). ' " /> </a>'; 

      } 
     } 
     else 
      $msg.="Query failed"; 
?> 
<div> 
<?php 
echo $msg; 
?> 
+2

充滿了安全漏洞。 – Boann 2015-08-16 17:55:51

1
if(isset($_POST['form1'])) 
{ 
    try 
    { 


     $user=$_POST['username']; 

     $pass=$_POST['password']; 
     $email=$_POST['email']; 
     $roll=$_POST['roll']; 
     $class=$_POST['class']; 



     if(empty($user)) throw new Exception("Name can not empty"); 
     if(empty($pass)) throw new Exception("Password can not empty"); 
     if(empty($email)) throw new Exception("Email can not empty"); 
     if(empty($roll)) throw new Exception("Roll can not empty"); 
     if(empty($class)) throw new Exception("Class can not empty"); 


     $statement=$db->prepare("show table status like 'tbl_std_info'"); 
     $statement->execute(); 
     $result=$statement->fetchAll(); 
     foreach($result as $row) 
     $new_id=$row[10]; 


     $up_file=$_FILES["image"]["name"]; 

     $file_basename=substr($up_file, 0 , strripos($up_file, ".")); 
     $file_ext=substr($up_file, strripos($up_file, ".")); 
     $f1="$new_id".$file_ext; 

     if(($file_ext!=".png")&&($file_ext!=".jpg")&&($file_ext!=".jpeg")&&($file_ext!=".gif")) 
     { 
      throw new Exception("Only jpg, png, jpeg or gif Logo are allow to upload/Empty Logo Field"); 
     } 
     move_uploaded_file($_FILES["image"]["tmp_name"],"../std_photo/".$f1); 


     $statement=$db->prepare("insert into tbl_std_info (username,image,password,email,roll,class) value (?,?,?,?,?,?)"); 

     $statement->execute(array($user,$f1,$pass,$email,$roll,$class)); 


     $success="Registration Successfully Completed"; 

     echo $success; 
    } 
    catch(Exception $e) 
    { 
     $msg=$e->getMessage(); 
    } 
} 
+0

儘管可以解決問題的代碼是可以接受的,但請添加一些解釋。 (儘可能小的例子也是一個好主意) – user5226582 2017-04-28 08:08:57

相關問題