Skip to main content

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.

Comments

Popular posts from this blog

Off-Page SEO – 7 Tips On How To Build BackLinks

Well a site cannot get expected traffic without doing seo in the world of completion. After introducing  on page seo . Now come back to introduce off page seo and basics of off page seo. As the word off page seo shows to do seo staying off from own page. Means to optimize a website from other sources. In simple a short we can define it as link building or creating backlinks. Off page seo helps site to get rank in search engines.   Fairly Off page seo is to create and build backlinks from several of ways. Off page seo is a hungriness of backlinks.”There so many ways to do off page seo or creating backlinks but now, let me show you how to build links to your pages: 1. Profile Pages Build Profile Pages in the top Social Media sites like: Google+ Profiles-           https://profiles.google.com            (A Must) Facebook Pages –     ...

August 6, 2017 CSE-PPT Professional Level - List of Passers (REGION XII)

August 6, 2017 CSE-PPT Professional Level  - List of Passers Civil Service Commission Regional Office No. 12 SOURCE: PRC ABALOS, ROMEO III G ABANG, CHRISTIAN MARK B ABAS, AMIRA A ABBA, BRYAN M ABDULADSIS, SAYEED MOHBEN K ABDULSATAR, SAHID M ABEAR, KRIZIA ANDREA Q ABELLON, SHIENA MAE F ABING, MARY SOL T ABOLENCIA, SEAN HOPE C ACIDO, DANIEL CARLO G ACUPAN, NONA MARIE P ADANG, SAIMA D ADELAN, MAILA LOUISA N ADVENTAJADO, CLYDELL S AGAD, LUCILLE ANGELIKKA DC AGAWA, YSA LOU S AGCARAO, APRIL BERNADETH P AGUILAR, RUTH D AGUJA, MARCO D AGURING, FROILAN J AJOC, LOVELL L AKIL, SAGUIRA M ALAMADA, SHAINETRA C ALAMAN, OMAR ADRIANNE P ALBARAN, GLORY GRACE C ALBRANDO, GERALDINE P ALCANTARA, KIMBERLY V ALCOBA, MARY ANN L ALCORDO, QUENNIE N ALDAVE, ANNABELLE JOY B ALLAGA, LOREN F ALLOSO, MERCY FE N ALMOJALLAS, JAN MARIE MAY J ALONZO, CHARMAINE KLAIRE A ALTIZO, ALEN JANE E ALURAN, ELLEN JANE C ALVAREZ, NEALL DOMINICK T AMAN, JOHN PAUL C AMANDE, JOEVEN A AMBAY, ARRIZ PAULA D AMER, ABJUHARY H AMINO, ...

Future Pinoy scientists, a Museum of Natural History

Michael Purugganan, when he was an elementary student at Union Science Elementary School in Malate, used to sneak into the National Science Development Board premises, where he would spend hours in a small museum.  "It just fascinated me. I just wanted to learn more about these things and what these people were doing there," Purruganan told GMA News Online.  "That was really what inspired me to become a scientist," said Purugganan, who is currently the Dean for Science at New York University and a world leader in evolutionary and ecological genomics.   With a new museum in the works, more young Filipinos may be inspired to become scientists. In a couple of years, the Philippines will have its own world class Museum of Natural History, showcasing endemic plants and animals that can be found in the country, according to a report on State of the Nation on January 23. Museums bridge the past and present, but the government believes these can also meet...