Thursday, 28 June 2012

Insert Image In MySQL Database Using PHP Language

This simple tutorial is about inserting or storing image to database. One example is updating user's avatar. We take some image to our computer and upload to the site. Some web site take your image and store it in a folder but for this we will use the database for storage. We are using PHP as our language and MySQL for our database.

First, set-up our table named pics.
For now, I suggest that you will create this table in test database because in example PHP source code below I use the test database, but you can still create your own.

1CREATE TABLE pics (
2 row_id  INT            NOT NULL AUTO_INCREMENT PRIMARY KEY,
3 name    VARCHAR( 30 )  NOT NULL,
4 size    INT            NOT NULL,
5 type    VARCHAR( 10 )  NOT NULL,
6 content BLOB           NOT NULL
7)
From the sql above you can notice the blob field. A blob (binary large object) is a data type for storing images, audio or other multimedia.

MySQL Blob data types, usage depends on the amount of data to be store.

   1.  BLOB
   2. TINYBLOB
   3. MEDIUMBLOB
   4. LONGBLOB

PHP Source Code
01<?php
02 
03// Connect to database
04 
05// Make a MySQL Connection
06  mysql_connect("localhost","root",""or die(mysql_error());
07  mysql_select_db("test"or die(mysql_error());
08 
09// Insert any new image into database
10 
11if(isset($_POST['xsubmit']) && $_FILES['imagefile']['name'] != "") {
12  $fileName $_FILES['imagefile']['name'];
13  $fileSize $_FILES['imagefile']['size'];
14  $fileType $_FILES['imagefile']['type'];
15  $content  addslashes (file_get_contents($_FILES['imagefile']['tmp_name']));
16 
17  if(!get_magic_quotes_gpc()) {
18    $fileName addslashes($fileName);
19  }
20 
21  // Checking file size
22  if ($fileSize < 150000) {
23    mysql_query ("insert into pics (name,size,type,content) "
24   "values ('$fileName','$fileSize','$fileType','$content')");
25  else {
26    $err "Too large!";
27  }
28}
29 
30// Find out about latest image
31 
32$gotten = mysql_query("select * from pics order by row_id desc");
33$row    = mysql_fetch_assoc($gotten);
34$bytes  $row['content'];
35 
36// If this is the image request, send out the image
37 
38 if ($_REQUEST['pic'] == 1) {
39   header("Content-type: $row[type];");
40 print $bytes
41 }
42?>
43 
44 
45<html>
46<head>
47<title>Upload an image to a database</title>
48</head>
49<body>
50  <font color="#FF3333"><?php echo $err ?></font>
51  <table>
52    <form name="myform" enctype="multipart/form-data" method="post">
53      <tr>
54        <td>Upload <input type="file" name="imagefile">
55          <input type="submit" name="xsubmit" value="Upload">
56        </td>
57      </tr>
58      <tr>
59       <td>Latest Image</td>
60      </tr>
61      <tr>
62        <td><img src="?pic=1"></td>
63      </tr>
64    </form>
65 </table>
66</body>
67</html>

From source code...
enctype="multipart/form-data"

enctype - determines how the form data is encoded. Whenever data is transmitted from one place to another. Music translated to music when uploaded, the same with other files.

Enctype attribute values:

1. application/x-www-form-urlencoded - All characters are encoded before sent (this is default).
2. multipart/form-data - No characters are encoded. This value is required when you are using forms that have a file upload control.
3. text/plain - Spaces are converted to "+" symbols, but no special characters are encoded.


header("Content-type: ");

header() - function to sends raw HTTP header to client.
Content-type - tells the browser what kind of file you're sending it. Example is text/html which display html page, or application/pdf which display pdf page or download it as PDF file.


<img src="?pic=1">

The image source will access the page it self again. Since we have condition if our code:
if ($_REQUEST['pic'] == 1) {...}
it will modify the page header converting the page to image content and store to image tag, that is why we have a new image.

0 comments:

Post a Comment

Internet-PublicLab. Powered by Blogger.