Google Custom Search

Storing Images in Mysql Database

Tutorial Outline:
  1. Creating a Test Mysql Database
  2. Example php Database Function
  3. Explanation of Database Function
  4. Php Script to Load Images in Mysql Database
  5. Explanation of Image Script
See Also:
  1. How to Get Images Out of MySql Database
  2. PHP Manual "base64_decode()"
  3. PHP Manual "chunk_split()"
  4. PHP Manual "convert_uuencode()"
  5. PHP Manual "RFC 2045 section 6.8"

This tutorial covers a simple way to store images in a mysql database. The example scripts that I provide here are intended to show you how to get a single image into your database. It will be up to you to write other scripts using php loops -- and functions like:

Creating a Test Mysql Database

This tutorial includes a fictitious database and table. Lets call the database test_imgs with a single table called pictures.

id pics ext gender
1 retergfghfghterhgcfnt
jpg female
  1. "id" is primary, key, not null, and auto_increment
  2. "pics" blob not null
  3. "ext" is varchar(4) not null
  4. "gender" is varchar(7) not null
  5. Mysql defaults for everything else.
  6. Create a directory "test" for the scritps
  7. Practice script "test.php"

Example Php Database Function

First let's write a function to connect to the Mysql database

Explanation of Database Function

I named my function "database connect" for obvious reasons, then passed the following arguments:

  1. $db_host -- Database Host
  2. $db_user -- Database User Name
  3. $db_pw -- Database Password
  4. $db_name -- Database Name
  5. &$db_selected -- Passed by reference
  6. &$connection -- Passed by reference

Arguments 1 through 4 need no explanation. Five and six were passed by reference which allows me to retrieve the variable values outside the function. Comment out the "die()" functions when you are not troubleshooting your code.

Php Script to Load Images in Mysql Database

Now lets get down to the task of storing images in a mysql database.

Explanation of Image Script

Notice that I used "fopen(), fread(), and fclose()" to get the contents of "testpic.php" and store it in a variable -- $img.

Next, I take $img and run it through "base64_encode().Read about base64 here.

Finally, after a little SQL magic, I place the encoded data from my test picture into the database. Viola! Now I have a jpeg image stored in mysql. Make note that I made a point to record the file extension along with the picture itself. I will be using that information when I am ready to get images out of my sql database.

Author: D.Shaun Morgan

How To Make Browser Go Back To Last Page With Using Php

How To Make Browser Go Back To Last Page With Php8/12/2014After submitting an HTML form or clicking a link encoded with variables and information, it is often desirable to the programmer that the user's browser be automatically redirected - to go back to the previous page. The simplest way I've found to accomplish this is by using a php built-in function called - header() and a PHP built-in variable called $_SERVER['HTTP_REFERER']

Binary Search User Functions

Binary Search User FunctionThe code in the example is for finding a given value in a sorted array.If the value is not found the function will return the position of the location where it the value should be.

Php Conditional Statments If Else Switch

Conditional Statements If Else & Switch CaseIf ElseIf else is the bread an butter of programming - so-to-speak. if-else and Case Switch are known as conditional operators; they create conditions or criteria that a block of code must meet in order to accomplish a certain task. Conditions make up the logic of a script.When writing scripts there is usually a need to compare something or make a decision, for e

Textarea Code Overflow

Textarea Code Overflows and Runs Out Onto PageMy Decision to Use Textarea TagWhile working on a script for to edit content, I ran into few problems. First - because mrarrowhead is a website about building websites using php, I have had to battle with the best way to display the example code on my webpages.I tried using the HTML special chars & lt; and & gt; respectively but I found it much too time consuming and tedious trying to convert the HTML code ba

Convert Timestamp To Readable Date Time Using Php

Convert Unix Timestamp to Readable Date Time PHPUser Functionstring function convert_timestamp(string $file_in, int $column,string $dateformatReturnsReturns a string representation of the file with one column convertedstring $file_inPath To the Fileint $co

Creating Image Watermarks

Creating PHP Watermarks$my_image = imagecreatefromjpeg('photo.jpeg');$watermark = imagecreatetruecolor(100, 70);imagefilledrectangle($watermark, 0,0, 99, 99, 0x0000FF);imagefilledrectangle($watermark, 9,9, 90,60, 0xFFFFFF);$my_image = imagecreatefromjpeg('photo.jpeg');imagestring($watermark, 5, 20, 20, 'libGD', 0x0000FF);imagestring($watermark, 3, 20, 40, 'watermark', 0x0000FF);$marginRigh

Need To Print Out An Array Using Php

How toPrint PHP ArraysThings to Consider AreArray Type- Single Array or Multidimensional Array?Class-Object Array?Raw Dump of Array Keys and Values?Array Data Precision Extraction Methods?Formatted Array Data - HTML tags - Str

Odd Number Php Script

Testing for Odd/Even Numbers - PHPExample - Banner Rotation PHP Script Odd/Even NumbersSimple Php Tutorial Creating Odd / Even Testing% modulus operator.$_SESSION['x'] % 2;In this example I will demonstrate a php script that I use to rotate two Ad banners.This results in a script that changes up the banner every time the user clicks

Using Php Cookies Variables

Using Cookie Variables in PHPSetting cookies in php is pretty straight forward. There is a php functionsetcookie();This function must be called before any anything else on the page or it will fail. There are two options to address this.Use ob_start to Buffer contentYou can either make sure that setcookie() is the first thing you call in your script - which is often just not a possibility.

How To Unzip Files On Your Free Hosting Account

Uzipping Files on Your Web ServerIf you are using a free hosting account with and many of the other Free hosts out there, you may have found that they don't offer you a lot of features. One feature that I could not find on free hosting accounts was a utility that would unzip my files after I uploaded them to my server. I had a dating site software that I was trying to install after I uploaded the zip files to my hosting server.Thus, I wrote a PHP

Passing Data From One Form To Another Form Using Php

Passing data from one form to another formTo pass php data from a form and then catch that data into another form one way to accomplish this task is to intermingle your php code into your HTML to dynamically capture variable values. This particular method is useful in a scenario where the user updates something via a post (it could be a text file or database) and then the user is returned to the page where the form is located to find various fields popula

Just In Time Compiling

JIT - Just in Time Compilers JIT refers to a special software that is found in web-browsers, and scripting engines such PHP's Zend. (My understanding of ZEND is that it produces byte-code and functions similar to other JIT compilers). For this discussion, without trying to be overly technical on what a JIT is or isn't -- JIT will simply mean software that turns scripts into executable code for whatever machine it is running on. The concepts of JIT and it's various

Storing Image Locations Mysql

Store Image URL in DatabaseRetrieve Image with PHP Script Saving URL Text in Database Saving image filesystem paths, of an image file in the database is easier than saving the whole image. Storing whole images requires converting the image files into bit-streams then saved into the database as binary and then changing them back into th

How To Turn Variable Value Into Variable Name

Variable Variables in PHPi-1Every so often when you are writing a php file, we all run into a situation where we would like for the name of the string that is inside of your php variable to be converted into the actual name of another variable. After a fair amount of hunting around the internet and getting sent off into PHP code hunting limbo for a few hours, I suddenly remembered that this was something that I had  found a solutio


Explanation of PHP Basic Syntax --New to PHPPhp is a language that is very much like writing c. The best feature of PHP versus c is that it is designed primarily to be used on WebPages -- allowing the author to intermingle their php code and the HTML on the same page. Being able to mix these two languages together provides a very flexible environment that allows the author to code some very nice dynamic content. PHP is called a server side scripting l

How To Use Dreamweaver

Dreamweaver - WISIWIGDreamweaver is a tool that arguably could be called the industry standard for web design.Dreamweaver, is an Adobe product that originally belonged to Macromedia. They sold out to Adobe a few years ago. I have been using Adobe/Macromedia Dreamweaver for about ten years. I am today using the Dreamweaver version that came packaged with Adobe CS 4. I started out with Dreamweaver 4. Since then Adobe has given this software a slightly different face and


Filezilla Ftp Client, FTP SERVER vs WsftpBy D.Shaun MorganWhile I was writing this article, about halfway through, I realized that it would be unfair to tell my readers about Filezilla without also mentioning another very good FTP client called WSftp. So, I backtracked and browsed over to website to take a look at the latest version. The fact is, when I first started building websites, WSftp was actually the first FTP client that I used. I don't know if Fil

Notepad Plus

Notepad++Download Notepad Plus Plus Notepad plus plus is an open source, free text editor. It is an ideal choice for many programming and scripting languages. Example - How to write c++ with Notepad Plus PlusExample - How to write HTML with Notepad Plus Plus

How To Open Create Write Files Using Php

Php file functions, Opening a file in php, reading a file in php, writing a file in phpIn this tutorial we will look at the most commonly used file functions used in php. The examples below should be pretty familiar to the seasoned php scripter, but they are useful nonetheless. We will end this tutorial with a php script and an html form that will read the contents of a file into a string variable and output it into a textfield for editing. You can try the script out be

Stop Form Spam Captcha

PHP -- How to Protect My Email Form / Contact Form Against Spam BotsAuthor D.Shaun MorganRandom Name Fields to Stop SpambotRandom Name Fields to Stop SpambotExample Random Name Fields ScriptExample Message ScriptStopping Spam Bot With

Retreive Images Mysql Using Php

How to get images out of mysql database with php and use them on my webpagesRetrieving Images From Mysql Database With phpAuthor D.Shaun MorganPHP Version - PHP 5xMysql Version - 5Tutorial OutlineDownload Test ScriptsCreating a Test Mysql DatabasePhp Script to

How To Make Money Online

Making Money on the InternetSign up for this series of free money making articles Name Email Since you are reading this I am going to assume that you are looking to either start or improve a venture of starting or improving yo

Store Images Mysql Using Php

Storing Images in Mysql DatabaseTutorial OutlineCreating a Test Mysql DatabaseExample php Database FunctionExplanation of Database FunctionPhp Script to Load Images in Mysql DatabaseExplanation of Image ScriptSee Also

Php Example Post Array

Visual example of how PHP handles the super-global array variable "$_POST"Author D.Shaun MorganVersions and Skill LevelPHP Version - PHP 5xReader skill level - BeginnerXHTML 1.0 Transitional - interchangeable with HTML 4.0See AlsoHow can I pass a PHP variable from one page

Php Arrays

Passing PHP ArraysHow to pass php variable arrays between pages.Author Author D.Shaun MorganSee AlsoHow can I pass a PHP variable from one page to anotherIn PHP progra

How To Write Php Functions

Explanation of a Basic PHP FunctionWhat is a PHP function?In PHP a function represents a block of instructions that perform a task. A PHP Function allows the user to re-use blocks of script without having to rewrite all the code every time it's needed. This is useful for repetitive tasks that perform the same jobs over and over.PHP has a large number of built-in function

How To Write Html Form Using Php

When learning PHP to build a website, one of the very first things that any newcomer, or beginner needs to learn is how to use HTML or XHTML ( will mean the same for this tutorial.) forms to collect information from users. Those data are usually email addresses, names, birthdays, and sometimes private information like credit card info, SSN, and home addresses. (The scripts in this tutorial are not meant for processing security sensitive data. It is only intended to teach you h

Register Globals Long Arrays

Security, php.ini, register_globals and register_long_arraysAuthor D.Shaun MorganVersions and Skill LevelPHP Version - PHP 5xReader skill level - ALLTutorial Outlineregister_globalsregister_long_arraysSee AlsoPHP Tutorials

How To Install Php 5

How to Install PHP 5.x.x.x on WindowsThis is beginner's how-to manual explaining how to quickly setup a PHP 5 installation on a Windows PC. You must have an Apache webserver installed and working on your personal computer.This tutorial was written primarily for configuring a test server.Below is a list of what you need before you start trying to install PHP.An Apache server installed and running (

Php Passing Variables

Pass Variables from One Page to Another -- PHPTutorial Outline Passing PHP variables with $_POSTPassing PHP variables in links with $_GETPassing PHP variables without POST or GET | $_SESSION
Google Custom Search

Leave a Comment




Enter The Captcha:

Author: Taz | Website URL: |
say if I'm trying to make a database in mysql that stores my products with a picture of each when a customer searches for products the info comes up with a small photo next to it...what is the easiest or simplest way this can be achieved??

Re: Admin
A simple way to do this is to create a table for for products and include field in that table that stores teh URL or file location of the picture for that product. This will allow you to store the images in the filesystem instead of in the database. Just pass along the file location to the html for images -- img src --. You could also add a field for the image's thumbnail location or take care of it in your php script.
Author: Shaun | Website URL: |
Great tutorials!
Author: rabi | Website URL: |
I love this tutorial! I was looking everywhere for this information! Finally I found it here.
Author: fatima | Website URL: |
how I can store image in DB and recieve from DB and show it?

Re: Admin

Images and Database
Author: phponwebsites | Website URL: |
Thanks. very easy to understand
Author: Dani | Website URL: |
Can you tell me how to insert more then one images in database?and how to store them in database? need a row for each file?

Re: Admin

If you use the image methods found at , you should be able to incorporate some type of loop such a for() or while() or do{} while(), etcetera.
Author: gayathri | Website URL: |
I have created a database table with two fields year type: area, yeild
when we select year and area and click submit we should get the image acording to those files how connect the images according to the fields when i select
show the

Re: Admin

Please explain a little more in depth about your problem. Are you having trouble getting the images into or out of the database, or are you haveing trouble writing a program that can return the exact images that you are requesting?
Author: hillary | Website URL: |
nice....thanks a lot
Author: Polin | Website URL: |
This is good but i have need more like image size and type restrictions and show with html and php. If possible please add more code. Thanks
Author: baluku mzee | Website URL: |
how to store images in mysl database using php and html, also automatic addation, substraction, making automatic calculation in above like after entering all products in the database then the total quantity sums up itself
Author: Kabir Ahmad | Website URL: |
plz tell me the way to save images along in the file and store its reference in database. plz also write the code. thanks
Author: Edgardo | Website URL: |
Woah I m really digging the template theme of this blog. It s simple, yet effective. A lot of times it s tough to get that perfect balance between user friendliness and visual appearance. I must say you ve done a awesome job with this. Additionally, the blog loads super fast for me on Safari. Excellent Blog
Author: kelechi | Website URL: |
1. please i have been trying to creat a social site where friends can view the comment of only those he she has as friend on the database. how do i manipulate the database so i can get the result using php on a local wampserver..
2. how do i terminate a session using php when a user just close a page without logging out.

please i will like you to send the reply to my email. thamks