如何使用php向数据库插入图像和从数据库检索图像 [英] how insert and retrieve images to and from database using php

查看:103
本文介绍了如何使用php向数据库插入图像和从数据库检索图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

im尝试上传会员资料的图片,并使用php将其存储在数据库中,然后检索它,但它对我不起作用

im trying to upload an image for a member profile and store it in a database using php then retrieve it but its does not work with me

这就是我要插入图像的内容:

this is what im trying for inserting the image :

<html>
<head>
<title> Upload an image </title>
</head>
<body>
<form action="index.php" method="POST" enctype="multipart/from/data">
  File:
  <input type="file" name="image" > <input type="submit" value="upload">
</form>
</body>
</html>
<?php

  mysql_connect("localhost", "root","") or die ("could not connect to the server");
  mysql_select_db("project") or die ("that database could not be found");

  $file = $_FILES['image']['tmp_name'];

  if (!isset($file))
     echo "please select file";
  else
  {

     $image= addslashes(file_get_contents($_FILES['image']['tmp_name']));
     $image_name = addslashes($_FILES['image']['name']);
     $image_size = getimagesize($_FILES['image']['tmp_name']);

     if($image_size == FALSE)
        echo "that not image ";

     else
     {

         if (!$insert= mysql_query("INSERT INTO user_info (image) VALUES ('$image')"))
             echo "Problem";

         else
         {

             echo "image: <p /> your image <p /><img src='view.php?id="id"'>";
         }
     }


 }

这是用于检索图像

<?php

   // do some validation here to ensure id is safe
   mysql_connect("localhost", "root","") or die ("could not connect to the server");
   mysql_select_db("project") or die ("that database could not be found");
   $id = addslashes($_REQUEST['id']);

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

   header("Content-type: image/jpeg");
   echo $image;
?>

推荐答案

我想您应该重新考虑您的工作.

I guess you should re-think what you are doing.

为什么将文件存储在mysql数据库中?我的意思是什么?

Why do you store files in a mysql database? I mean what is the point in that?

文件系统是用于存储文件的专家数据库. 因此最好不要将文件保存在普通数据库中,而应保存在文件系统中.

File system is an expert database for storing files. So better do not keep your files in a normal database but in the file system.

图像可以在目录(0102003.gif)中用数字命名,并且可以通过mysql记录中的文件名进行寻址.

Images can be named with numbers in directories (0102003.gif) and can be addressed via the filenames in your mysql records.

如果您确实需要将文件存储在数据库中,则mysql不是用于此的工具.

If you really need file storage in a database, mysql is not the tool for that.

看看mongoDB.

Have a look at mongoDB.

PS:不建议使用mysql接口,请使用mysqli或PDO.

PS: mysql interface is deprecated, please use mysqli or PDO.

这篇关于如何使用php向数据库插入图像和从数据库检索图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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