cómo insertar y recuperar imágenes hacia y desde la base de datos usando 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"'>";
         }
     }


 }

and this for retrieving the image

<?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;
?>

preguntado el 05 de mayo de 13 a las 09:05

Algo malo con echo "image: <p /> your image <p /><img src='view.php?id="id"'>";? -

@DaveChen but even if i remove it the code does not insert anything -

I highlighted a syntax error. Your script shouldn't have been able to run at all. -

@DaveChen ok i will do but why the insert does not work too ? -

5 Respuestas

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

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.

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

Si democracia need file storage in a database, mysql is not the tool for that.

Have a look at mongoDB.

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

contestado el 05 de mayo de 13 a las 09:05

Agreed! What about small sprites though? - Dave Chen

less than file page size?, Actually it is the same story, Database servers store blobs with page boundaries, so no difference on the size generally. why bother? - Volkan

Also having multiple images loaded into the PHP memory will more than likely end up causing "Out of Memory" errors. Save files to the file system, only store the path. - David

To store images on a php website, you just have to put the files in a directory and save the filenames on the mySQL database. Goodluck!

contestado el 05 de mayo de 13 a las 09:05

Try This code it will help you.

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

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

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

    mysql_query("INSERT INTO table1 (id,image) VALUES ('1','{$image}')");        
?>

Respondido 24 Feb 14, 06:02

Necesita enctype=multipart/form-data en su declaración de formulario. Y acceda al archivo a través de la variable $_FILES en lugar de la variable $_POST. Me gusta:

<form action="testimage1.php" method="post" enctype="multipart/form-data"> <input name="uploadimage" type="file" /> </form> <?php $filename = $_FILES['uploadimage']['tmp_name']; ?>

respondido 22 mar '14, 10:03

There are 2 different ways by which you can insert and retrieve images:

Método 1:

Store entire image in the database itself in longblob type and retrieve it from the database.

Insertar imagen:

<?php
//Get uploaded file data
$img_tmp_name    = $_FILES['image']['tmp_name'];
$img_name        = $_FILES['image']['name'];
$img_size        = $_FILES['image']['size'];
$img_type        = $_FILES['image']['type'];
$img_error       = $_FILES['image']['error'];
//Processed uploaded img data
if($img_error > 0)
{
    die('Upload error or No img uploaded');
}
$handle = fopen($img_tmp_name, "r");
$content = fread($handle, $img_size);
fclose($handle);
$encoded_content = addslashes($content);

$query="insert into user_info (img_content,img_type) values('".$encoded_content."','".$img_type."')";
$ex=mysqli_query($conn,$query);
if($ex){
    echo "image uploaded";
}
else{
    echo "image not uploaded<br/>".mysqli_error($conn);
}
?>

Retrieve image:

You can retrieve an image by 2 methods, first by using a handler PHP script to return the image data and the second one as follows:

<?php
    $query="select * from user_info WHERE id='".$id."'";
    $ex=mysqli_query($conn,$query);
    $row=mysqli_fetch_array($ex)
?>              
<img src="<?php echo "data:'".$row['img_type']."';base64,".base64_encode($row['img_content']); ?>" />

But method 1 is not a recommended way if the image size will be large.

Método 2:

In this method, we only store the path of the image in the database. We store the images in a directory.

Insertar imagen:

<?php
    $target_dir = "image/";
    $target_file = $target_dir . basename($_FILES["image"]["name"]);
    move_uploaded_file($_FILES["image"]["tmp_name"], $target_file);

    $query="insert into user_info (img_path) values('".$target_file."')";
    $ex=mysqli_query($conn,$query);
    if($ex){
        echo "image uploaded";
    }
    else{
        echo "image not uploaded<br/>".mysqli_error($conn);
    }
?>

Retrieve image:

<?php
    $query="select * from user_info WHERE id='".$id."'";
    $ex=mysqli_query($conn,$query);
    $row=mysqli_fetch_array($ex)
?>
<img src="<?php echo $row['img_path']; ?>" alt=""/>

respondido 17 mar '19, 05:03

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.