如何使用php脚本将图像上传到数据库? [英] How to upload an image to a database using php script?

查看:192
本文介绍了如何使用php脚本将图像上传到数据库?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这里是我上传的代码..但它不工作..我使用了一个file_get_contents函数..


上传图片

here is the code for my upload.. but it doesn't work.. I've used a file_get_contents function.. Upload image

</head>
<body>
    <form action="upload1.php" method="POST" enctype="multipart/form-data">
    File: 
    <input type="file" name="image"/> 
    <input type="submit" value="Upload image" />

    </form>

<?php 

//connect to the database
$con = mysql_connect("localhost","root", "");
if(!$con)
 {
 die('Could not connect to the database:' . mysql_error());
 echo "ERROR IN CONNECTION";
}

mysql_select_db("imagedatabase", $con);


//file properties

 echo $file = $_FILES['image']['tmp_name']; 
 echo '<br />';

 if(!isset($file))
echo "Please select an image";

else
{
$image = file_get_contents($_FILES['image']['tmp_name']);
echo $image_name = addslashes($_FILES['image']['name']); echo '<br \>';
echo $image_size = getimagesize($_FILES['image']['tmp_name']);

if($image_size == FALSE)
    echo "That's not an image";
    else
{
        $insert = mysql_query("INSERT INTO images (image) VALUES    ($image)",$con);
if(!$insert)
    echo "Problem uploding the image. Please check your database";  
else 
{
    $last_id = mysql_insert_id();
    echo "Image Uploaded. <p /> Your image: <p /><img src=display.php?        id=$last_id>";
    }
}

}
mysql_close($con);
?>

</body>
</html>

,并且检索/显示的代码以这种方式。

and the code for the retrieve/display goes this way..

<?php
 //connect to the database
 mysql_connect("localhost","root", "") or die(mysql_error());
 mysql_select_db("mydb") or die(mysql_error());

 //requesting image id

 $id = addslashes($_REQUEST['id']);

$image = mysql_query("SELECT * FROM images WHERE id = $id");
$image = mysql_fetch_assoc($image);
$image = $image['image'];

header("Conten-type: image/jpeg");

 echo $image;


 mysql_close($connect);
 ?>

我创建了一个名为imagedatabase和表格的数据库

I've created a database named 'imagedatabase' and a table

推荐答案

在数据库中存储图像是个坏主意。

That's a bad idea to store an image in database. Store a path to it in database, close directory with images via .htaccess and use it on a hard drive.

如果您将使用DB存储图像,您将拥有:

If You'll use DB to store images You will have:


  1. 慢查询

  2. 灾难性索引大小

  3. - > mysql

  4. 编辑照片时出现问题(您需要获取图片,修改某些内容
    ,然后重新插入所有数据哦

  5. 从一个地方传输文件到另一个地方的问题

  6. StackOverflow的新问题«如何处理文件,如果他们不是
    文件,但字符串»

  1. slow queries
  2. catastrophic indexes' size
  3. high load on bridge php<->mysql
  4. problems with edit photos(You'll need to get image, modify something and insert all data again. Ohh nooo)
  5. problems with transfer files from one place to another
  6. new question on StackOverflow «How to work with files if them not files, but a string»

这篇关于如何使用php脚本将图像上传到数据库?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆