Upload images to mysql database

metalix 0 Tallied Votes 1K Views Share

first create the table

create table images (
    image_id    serial,
    filename    varchar(255) not null,
    mime_type   varchar(255) not null,
    file_size   int          not null,
    file_data   longblob     not null,
    primary key (image_id),
    index (filename)
);

the file to output the images to the browser picsrc.php

<?PHP
//detect if image is called correctly
if($image){
//connect to db
    $db = mysql_connect('localhost', 'user', 'password');
//find the image
        $query  = sprintf('select * from images where filename = %d', $image);
        $result = mysql_query($query, $db);
$image = mysql_fetch_array($result);
//tell the browser the url is an image
    header('Content-type: ' . $image['mime_type']);
    header('Content-length: ' . $image['file_size']);
//finally output the image
echo $image['file_data'];
}
?>

to call the image use this line

<img src="picsrc.php?image=potato.jpeg">

fairly straightforward. you can view a full tutorial at http://www.effectivewebdesign.co.nz/tutorial.php

hope this helps.

<?php
//connect to database
    $db = mysql_connect('localhost', 'user', 'password');

//detect if form has been processed
 if($_FILES['image']){
  $image = $_FILES['image'];
//detect file is image
  $info = getImageSize($image['tmp_name']);
        if (!$info) {
            $notice = 'File is not an image';
        }
  else {
//insert the image
           $query = sprintf(
            "insert into images (filename, mime_type, file_size, file_data)
                values ('%s', '%s', %d, '%s')",
            mysql_real_escape_string($image['name']),
            mysql_real_escape_string($info['mime']),
            $image['size'],
            mysql_real_escape_string(
                file_get_contents($image['tmp_name'])
            )
        );
$notice = 'Image Uploaded successfully';
  }

 }
?>
<html><head>
<title>Upload an Image</title>
</head>
<body>
<h1>Upload an Image</h1>
<?PHP if ($notice){
//echo image status
 echo $notice;
}
?>
<br />
<a href="view.php">View uploaded images</a>
<form method="post" action="<?PHP echo $_SERVER['PHP_SELF']; ?>" enctype="multipart/form-data">
<input type="file" name="image" />
<input type="submit" value="Upload Image" />
</form>
</body>
</html>
metalix 0 Posting Whiz in Training

yes I realise it is in the wrong order.
It is difficult to put tutorials in code snippets :)

Rewired 0 Light Poster

Hey where is the

<a href="view.php">View uploaded images</a>

Code

metalix 0 Posting Whiz in Training

Yeah sorry I didn't put that one in.
you just call the images as you normally would (<img src="images/pic.jpg">)
but instead you'll have <img src="picsrc.php?image=myimage.jpg">

however I suggest you use a .htaccess mod rewrite and an url encoder so as to make it a little more secure (I removed security checks for simplicity)

guruparthi -6 Newbie Poster

You can use this code to upload images to database using PHP

 <form action="#" method="post" enctype="multipart/form-data">
File: <input type="file" name="file">
       <input type="submit" name="submit" value="Upload">
</form>
<?php
 if(isset($_POST['submit']))
 { 
   mysql_connect('localhost','root','');
   mysql_select_db('new');
   $name=$_FILES['file']['name'];
   $type=$_FILES['file']['type'];
   if($type=='image/jpeg' || $type=='image/png' || $type=='image/gif' || $type=='image/pjpeg')
   {
if(file_exists(dirname($_SERVER['DOCUMENT_ROOT']).'/oops/upload/image/'.$name))
     {
      echo'file is already present';
     }
     else
     {
      $up=move_uploaded_file($_FILES['file']['tmp_name'],dirname($_SERVER['DOCUMENT_ROOT']).'/oops/upload/image/'.$name);
      $q=mysql_query("insert into image values('','".$name."')");
  if($up && $q)
  {
   echo'image uploaded and stored';
  }
  elseif(!$up) 
  {
   echo'image not uploaded';
  }
  elseif(!$q)
  {
   echo'image not stored';
  }
 }
   }
   else
   {
    echo'Invalid file type';
   }
 }
?>
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.