1. Home
  2. Computing & Technology
  3. PHP / MySQL

Upload a File and write to MySQL

By Angela Bradley, About.com

3 of 4

Processing the Data

<?php

//This is the directory where images will be saved
$target = "images/";
$target = $target . basename( $_FILES['photo']['name']);

//This gets all the other information from the form
$name=$_POST['name'];
$email=$_POST['email'];
$phone=$_POST['phone'];
$pic=($_FILES['photo']['name']);

// Connects to your Database
mysql_connect("your.hostaddress.com", "username", "password") or die(mysql_error()) ;
mysql_select_db("Database_Name") or die(mysql_error()) ;

//Writes the information to the database
mysql_query("INSERT INTO `employees` VALUES ('$name', '$email', '$phone', '$pic')") ;

//Writes the photo to the server
if(move_uploaded_file($_FILES['photo']['tmp_name'], $target))
{

//Tells you if its all ok
echo "The file ". basename( $_FILES['uploadedfile']['name']). " has been uploaded, and your information has been added to the directory";
}
else {

//Gives and error if its not
echo "Sorry, there was a problem uploading your file.";
}
?>
This code should be saved as add.php. To understand what each step of this script is doing it is best to read the comments within the code. Basically it gathers the information from the form and then writes it to the MySQL database. Once that is done, it saves the file to the /images directory (relative to the script) on your server.

If you are only allowing photo uploads, you might consider limiting the allowed file types to jpg, gif and png. We also don't check if the file already exists, so if two people both upload a file called MyPic.gif, one will overwrite the other. A simple way to remedy this would be to simply rename each file with a unique ID.

Explore PHP / MySQL
About.com Special Features

Stay connected and entertained with reviews on tips on the latest HDTVs, cellphones and more. More >

Easy ways to connect two computers for networking purposes. More >

  1. Home
  2. Computing & Technology
  3. PHP / MySQL
  4. PHP with MySQL
  5. Upload a file to your server and add it's details to MySQL - SQL Upload File

©2009 About.com, a part of The New York Times Company.

All rights reserved.