For this month’s 12412 project, I wanted to create a simple submission site in order to play around with MySQL and PHP, which really isn’t something I’m too strong in right now. I ended up creating Royal United, a photo submission site for displaying photos of the UK (one of my favorite topics of photography!).

This site was actually a lot simpler to create than I anticipated and only needed a bit of help from Nikita (my PHP programmer hubby). This tutorial assumes a basic knowledge of PHP and aimed at beginners.

The Structure

You’ll need to start out by creating a new database, let’s call it “photosite”. You’ll then need to create a new table, called “photos”. You won’t need to enter any actual MySQL, as all of this can be done by following buttons in the standard PHPMyAdmin UI.

The structure for the table is quite simple. We want to give each photo a unique ID, we’ll need the image URL, plus we’d like to capture where the photo is located and when it was uploaded.

Create a column called “id” and give a type of int(eger) and make sure “auto_increment” is selected. This was auto assign a unique number to every photo that’s uploaded. Two more columns called “image” and “location” needed to be created, with the type of “text”. Finally add the last column called, “dateAdded” and give it a type of date.

Connect to the Database

You’ll need to start by connecting to the database. It’s important to put this information in it’s own PHP file so it’s more secure. Start a php file and called it “connect.php” and add your credentials to:


<?php mysql_connect('localhost', 'database-username', 'database-password') or die(mysql_error());
mysql_select_db("database-name") or die(mysql_error()) ; ?>

Create a new file called “index.php” and require this file at the very top:

The HTML

It’s now time to move on to the HTML. How you want to design this is completely up to you, and I recommend you get this down before you start programming. What you must have is a form for users to upload their photos and put in the location it’s been taken from. You can do this with a very basic HTML form:


<form action="index.php" method="post" enctype="multipart/form-data">
	<input type="hidden" name="xsubmit" value="y"/>
	<input type="file" name="file" id="file" />
	<input type="text" name="location" id="location" placeholder="Click to add location" />
	<input type="submit" name="submit" value="Upload" />
</form>

We’ll set the form’s action to index.php, because we want the site to stay on the same page after the photo’s uploaded. In order to do this, we’ll need to add a hidden input field so we can check if the form has been submitted. Then we’ll just add basic file inputs and text fields.

Uploading Photos

Using the hidden field, we’ll check to see if the form has been submitted, if it has, we’ll then need to make sure it’s an actual image (so no hackers or spammers!) and then make sure it’s not over a certain file size. If the uploaded information passes all of those checks, it then needs to save into the database so we can retrieve and display it later. Create a file called “upload.php”.

Firsts add the checks:


<?php

// Checks to see if the form has been submitted
if ($_POST['xsubmit'] == 'y') {

        // Checks to see if the file is a gif, png, or jpg, and if it's under 2MB
	if ((($_FILES["file"]["type"] == "image/gif")
	|| ($_FILES["file"]["type"] == "image/jpeg")
	|| ($_FILES["file"]["type"] == "image/jpg")
	|| ($_FILES["file"]["type"] == "image/png"))
	&& ($_FILES["file"]["size"] < 2000000))
	{
	    // If file passes checks, do something
	}
}
?>

Now let’s save the image into the database. In order to avoid overwriting files if users upload an image with the same name, we’re going to append the date to the name of the file:


<?php
	//This is the directory where images will be saved
	$target = "images/";
	$target = $target . basename( $_FILES['file']['name']);
	$target = explode(".", $target);
	$target = time().'.'.array_pop($target);
?>

We’ll now assign variables to the location and image


<?php
//This gets all the other information from the form
$location=$_POST['location'];
$image=($_FILES['file']['name']);
?>

Now we’ll need to connect to the database by including our connect.php file. We’ll write a msql_query to insert our variables ($location, $target) into the database. We’ll also add the date with the appropriate timezone into the “dateAdded” field.

If the file has been added successfully, you’ll get an ok message, or an error if something went wrong:


include_once('lib/connect.php');

		//Writes the information to the database
		mysql_query("INSERT INTO photos (location,image,dateAdded)
		VALUES ('$location', '$target',DATE_ADD(NOW(), INTERVAL 5 HOUR))") ;

		//Writes the photo to the server
		if(move_uploaded_file($_FILES['file']['tmp_name'], 'images/'. $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.";
		}

The entire upload.php file should look like:


<?php

if ($_POST['xsubmit'] == 'y') {

	if ((($_FILES["file"]["type"] == "image/gif")
	|| ($_FILES["file"]["type"] == "image/jpeg")
	|| ($_FILES["file"]["type"] == "image/jpg")
	|| ($_FILES["file"]["type"] == "image/png"))
	&& ($_FILES["file"]["size"] < 2000000))
	{

		//This is the directory where images will be saved
		$target = "images/";
		$target = $target . basename( $_FILES['file']['name']);
		$target = explode(".", $target);
		//print_r($target);
		//die;
		$target = time().'.'.array_pop($target);

		//This gets all the other information from the form
		$location=$_POST['location'];
		$image=($_FILES['file']['name']);

		include_once('lib/connect.php');

		//Writes the information to the database
		mysql_query("INSERT INTO photos (location,image,dateAdded)
		VALUES ('$location', '$target',DATE_ADD(NOW(), INTERVAL 5 HOUR))") ;

		//Writes the photo to the server
		if(move_uploaded_file($_FILES['file']['tmp_name'], 'images/'. $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.";
		}
	}
}
?>

Displaying the Items

Displaying the photos is actually quite simple. We’ll connect again to the database and create a foreach loop to go through every item in the database to display the information. I’ve added comments to the code to explain what each section does.


<?php
// Select the items from the database
$query="SELECT * FROM photos ORDER BY dateAdded DESC, id DESC";
$result2=mysql_query($query);

// Close the connection
mysql_close();

// Add the items to an array
$datePhotos = array();
while ($result = mysql_fetch_array($result2)) {
	$datePhotos[$result['dateAdded']][] = $result;
}

// Go through array and display each photo
foreach ($datePhotos as $date => $photos){
	foreach ($photos as $photo){
		$imageURL = $photo['image'];
		$locationText = $photo['location'];

                // display the image and location
		echo "<a rel="group1" title="Taken in $locationText" class="photo" href="images/$imageURL"><img src="images/$imageURL" alt="Taken in $locationText"/><span>$locationText</span></a>";

	}
}

?>

What’s Next

That’s pretty much it! This project was a lot simpler than I originally thought it was going to be. April’s 12412 is going to be dedicated to adding pagination and some kind of loading so the site can load a lot faster than it does now.

Amber Weinberg

Amber is a freelance front-end developer specializing in semantic and accessible custom WordPress themes. She works with agencies and other freelancers to bring their designs to life using custom ACF flexible layout builds - making them more performant and less buggy while allowing the client easy customization without breaking the design system.