Developers: How to upload an image to MySQL via PHP

Reading time icon 2 min. read


Readers help support MSPoweruser. When you make a purchase using links on our site, we may earn an affiliate commission. Tooltip Icon

Read the affiliate disclosure page to find out how can you help MSPoweruser effortlessly and without spending any money. Read more

Since I spent my entire day (literally, no joke) trying to add online photo sync to Power Planner, I realized someone needs to write a guide on how to upload pictures from WP7 to a MySQL database via PHP!

After a LOT of trial-and-error and a ton of searching, here is what I found works. You can download the files at the end of the post (that way you can copy/paste stuff).

First of all, I created a helper class called Sync that will manage uploading and downloading images from my server. In the Sync class, I will use a method called UploadImage which takes a file name of an image already saved in the app’s isolated storage.

More after break:

Notice that I also read the file stream into a private byte array. This data is used in the next method, for writing the image data into the upload.

And finally I get the response from the server once the image uploaded…

Easy enough, right? Make sure you set the content type to image/jpeg. If you don’t, larger picture uploads will error out. Now onto the PHP/MySQL side of things.

First configure your database with a new table. Give it an Id INT column, FileName TEXT , and Data MEDIUMBLOB column. You want to use MediumBlob because I hear normal Blob doesn’t even hold more than 1 MB. Anyways I haven’t researched into that, but MediumBlob should hold 16 MB I believe.

Now the PHP file.

Dang that was easy! You must use addslashes on the uploaded data file. Otherwise it won’t insert into your database. However, when you’re downloading the image, do not use stripslashes or else you’ll get a corrupted jpeg.

I’ll write another post on how to download the image back to your phone sometime tomorrow.

In the meantime, download these files in a zip if you want to copy/paste the code! I also included thorough comments in the code and made it more detailed.

More about the topics: code sample, developers

Leave a Reply

Your email address will not be published. Required fields are marked *