How to upload image to MySQL using AJAX and PHP?
How to upload image to MySQL using AJAX and PHP? On this question I will answer in this post.
Recently I was doing tablet application and I needed the solution to transfer pictures uploaded by customer to database.
Below I will try to explain how I did it localy on my XAMPP.
What do you need?
First we need to create database in my PHPmyAdmin ( in your local host Xampp).
To do it you can either download full code with my sql file attached and use Import feature in phpMyAdmin or you can create it yourself.
Database name is upload and table name is photo.
My photo table consists from photoid which is INT and location which is VARCHAR .
If you want to know more about SQL data types you can have a look on this link
Step 1 ( like on picture above ). Create new database and name it upload
Step 2 Go to SQL tab and pass the below code and press Go.
upload.sql
Step 3 You can leave your php Admin because now we will explain other files. Overall your files should look like that:
Upload – there will go our uploaded images so you can view them in db but also in that folder.
Our Db called upload will have table called photo in which we will have 2 colums: photoid ( id of our image starting from 1 ) and location ( path to our upload folder where the pictures will be available for viewing ).
Let’s start to create our files!
conn.php
creating connection to our database which we called upload. Please have in mind that connection is set up to default settings of Xampp where user is root and there is no password. If you ever gave your locahost a new user name and a password you should change it accordingly $conn = mysqli_connect(“hostname”, “username”, “password”, “database”);
index.php
We create our upload form and we show the images uploaded in this page.
fetch_photo.php
upload.php
-uploading images into our database.
custom.js
-contains our jQuery and AJAX code in uploading and fetching our images.
Hope you learned something new
If you learned something new from this tutorial or if you have any question let me know in comments section.
I will be more then happy to assist you.