Building the back-end of a photo site
videos

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();
    
    			$(this).fadeOut(100).before('');
    		
    		    $('#input').livequery('change', function() {
    	            var id = <?php echo $_GET['id'] ?>;
    			    var thisparam = this;
                    var newText = $(this).val();
                    
                    if (newText == '') {
                       newText = 'Please enter a description'; 
                    }
                              
    	            $.ajax({
    	                type: 'post',
    	                url: 'updatePhoto.php',
    	                data: 'id=' + id + '&description=' + newText,
    	    
    	                success: function() {
                            $(thisparam).remove();
    	                    $(originalelement).text(newText).fadeIn(1000);
    	                }
    	           });
                    
    		    });
    		});
    	});
    

    UpdatePhoto.PHP

    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);
    			   	
    			$.ajax({
    				type: 'post',
    				url: 'delete.php',
    				data: 'id=' + id,
    				
    				success: function() {
    		
    					$(thisparam).parent('li').fadeOut('slow');
                        $('#result').remove();
    					var response = '

    Success. The image has now been removed!

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

    Delete.PHP

    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");
    

    Completion

    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.

    Note: Want to add some source code? Type <pre><code> before it and </code></pre> after it. Find out more
    • http://infriends.tk Titto

      Haiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiii
      This code is better
      I Like this

      Thanks admin

    • bummelum

      I came here by mistake, but immediately spotted the obvious sql-injection flaw in delete.php. Either check that the value of $_POST['id'] is actually numeric using is_numeric(…), or do a simple typecast:

      $id = (int)$_POST['id'];

      to ensure an int value.