Building the Back-End of a Photo Site


For those of you who have been following the last few screencasts, you must have noticed that each tutorial has been centered around a "photo site" theme. (See Scanning Folders With PHP, How to Dynamically Create Thumbnails, and Create a Photo-Admin Site Using PHP and jQuery. Today, we'll build the backend for a photo site. This tutorial will teach you how to add, delete, and update photos.

Our Mission

  • Create a database that will store our images.
  • Create a home page that retrieves all of the photos that are stored in our database.
  • Allow the user to upload photos.
  • Write some validation to ensure that the user enters a proper description and chooses an image
  • Use jQuery to allow the user to asynchronously update and delete specific photos.

There is simply too much to cover as a written tutorial. I've included a few key points. Refer to the screencast for the complete tutorial.

The Database Structure

The database structure

Get the Photos From the Database

Get Photos Function
function getPhotos() {
	require 'database.php';
	$q = "SELECT id, tn_src FROM photo ORDER BY id desc";
	$result = $mysqli->query($q) or die($mysqli_error($mysqli));
	if($result) {
		while($row = $result->fetch_object()) {
			$tn_src = $row->tn_src;
			$src = $row->src;
			$id = $row->id;
			print '
  • <a href="review_image.php?id=' . $id . '"> <img src="' . $tn_src . '" alt="images" id="' . $id . '" /> </a> </li>'; print "\n"; } } }
  • Upload Photos

    Get Photos Function

    Form Validation

        if(strlen($_POST['description']) < 4) 
        $error['description'] = '

    Please enter a description for your photo.

    '; if($filename == '' || !preg_match('/[.](jpg)|(gif)|(png)|(jpeg)$/', $filename)) $error['no_file'] = '

    Please select an image, dummy!


    Update the Photo's Description Asynchronously

    Get Photos Function
    $('#description').click(function() {
                var originalelement = this;
                var currentText = $(this).text();
    		    $('#input').livequery('change', function() {
    	            var id = <?php echo $_GET['id'] ?>;
    			    var thisparam = this;
                    var newText = $(this).val();
                    if (newText == '') {
                       newText = 'Please enter a description'; 
    	                type: 'post',
    	                url: 'updatePhoto.php',
    	                data: 'id=' + id + '&description=' + newText,
    	                success: function() {


    require 'database.php';
    $id = $_POST['id'];
    $d = addslashes($_POST['description']);
    if ($d == '') $d = 'Click here to enter a description.';
    $q = "UPDATE photo SET description='$d' WHERE id = $id"; 
    $result = $mysqli->query($q) or die('There was a problem updating this information.');
    if($result) echo "Your photo has been successfully updated.";

    Delete a Photo

    Get Photos Function
    	$(function() {
    		$('img').click(function() {
    		   	var id = $(this).attr('id');
    		   	var thisparam = $(this);
    				type: 'post',
    				url: 'delete.php',
    				data: 'id=' + id,
    				success: function() {
    					var response = '

    Success. The image has now been removed!

    '; response += 'Return to Home Page
    '; $('body').append(response); } }); }); })


    require 'database.php';
    $id = $_POST['id'];
    $q = "DELETE from photo WHERE id = $id";
    $result = $mysqli->query($q) or die("There was a problem!");
    if($result) header("location: index.php");


    So that does it. You could implement a bit more security into this application. But the idea is that these pages would already be secured by using something similar to an ht-access file. From here on, the sky is the limit. You should consider adding tags to your images, creating albums, etc. This should get you started.

    Related Posts
    • Code
      Creative Coding
      Using WordPress for Web Application Development: Custom Database QueriesApplication foundation 400
      Throughout this series, we've been looking at the various facilities that make it possible to treat WordPress as a foundation for web application development. Thus far, we've covered a lot of ground: We've talked about how WordPress is more of a foundation rather than a framework. We've discussed the nature of the the Event-Driven Design Pattern. There's been a discussion of Email, User Management, Saving Data, Retrieving Data ...and more. In the most recent articles, we've been talking a look at how to handle queries against the WordPress database through the use of WP_Query and WP_User_Query.Read More…
    • Code
      Building a Customer Management App Using AngularJS and LaravelLaravel 4 auth retina preview
      When creating a single-page app we should use some kind of framework to do some of the job for us, so we can focus on the actual functionality. AngularJS fits here perfectly, because features like dynamic dependency injection and bi-directional data binding are just great. Sometimes we also require some kind of server. If you've chosen PHP then Laravel may be your best option, as it's easy to work with and pretty powerful.Read More…
    • Code
      Creating a Photo Tag Wall With Twilio Picture Messaging & PHPProcedural to oop php retina preview
      Twilio's recently announced Picture Messaging has vastly opened up what we can do with text messaging, now we can attach photos to our text messages and have them get used in different ways. In our case, we are going to build a Photo Tag Wall, which will contain photos linked to tags that will be displayed on a website.Read More…
    • Code
      JavaScript & AJAX
      Working With IndexedDB - Part 2Indexeddb retina preview
      Welcome to the second part of my IndexedDB article. I strongly recommend reading the first article in this series, as I'll be assuming you are familiar with all the concepts covered so far. In this article, we're going to wrap up the CRUD aspects we didn't finish before (specifically updating and deleting content), and then demonstrate a real world application that we will use to demonstrate other concepts in the final article.Read More…
    • Code
      Building a CodeIgniter Web Application From Scratch - Part 1Web app retina preview
      In this series we're going to build a web billboard application from scratch, we're going to use CodeIgniter to handle the back-end service and BackboneJS for the web client. In the first two parts of the series we'll create the back-end service and then the client application in the last two.Read More…
    • Code
      How to Create a WordPress Avatar Management Plugin from Scratch: Finishing TouchesPreview
      Avatar Manager for WordPress is a sweet and simple plugin for storing avatars locally and more. Easily. Enhance your WordPress website by letting your users choose between using Gravatar or a self-hosted avatar image right from their profile screen. Improved workflow, on-demand image generation and custom user permissions under a native interface. Say hello to the Avatar Manager plugin.Read More…