menu

Sunday, December 26, 2010

Making your own PHP based Image Gallery with AJAX and Light-box2

Hello everyone,

Ahh after a very long time, ma exams over and i'm doing like hell these days :D
Anyway recently i got to make our site [for the 4th time] so i though to give it a real change.
So here i'm to make a new php Gallery for the graphic section. I just wanted to make the hell out by myself so can alter it my way :D


Let's get started.

Steps:
1) Make a simple php script that can retrieve the records about images from the database and do the dynamic page breaking.
2) Adding the lightbox to have a little show off Big Grin
3) Adding the AJAX part

1) PHP script

First thing we need is to make a php script that can retrieve all the records about the images and do page breaking. Here i used to store the info in a database rather than reading directly from a folder. This makes it possible for me to add an image description. So, when i retrieve the images possibly i want to do the dynamic page breaking, adding the pages automatically so there's no mess there. 

First make a folder name "res" and add some pics to it. 
Then in your database make a new table "images"
Add 3 fields, 
*ID [auto increment], 
*Img - path to the image
*Desc - Description of the image
After add some record to it
I added 10 for the testing purposes

Now the php script
Make a file named view.php
NOTE: I have used CSS styling here so be patient to see the CSS style after this code Big Grin

[view.php]

Code:
<?php

$start = 1;     // This is the variable that stores the current page of the gallery. Default its set to 1 to prevent errors

$page_name = "view.php"; //The name if added to make things easier

if(isset($_GET['q']))$start = $_GET['q']; //Check weather a variable is passed to page, if so it become the current page number.

$limit = 5;  //Number of pictures that should be shown per page
$eu = (($start-1) * $limit);  //Get the offset to be used in Mysql query, dont bother about it :D

$conn = mysql_connect(db_host,db_user,db_pwd);   //Connecting to the databse, put the necessary variables. Ex: db_host replace with "127.0.0.1"

if(!($conn)) echo "Failed To Connect To The Database!";
else{
   
    if(mysql_select_db(db_name,$conn)){  //Check weather databse exists

//From here we first do the page breaking as it takes the big deal of the script

    $no = mysql_num_rows(mysql_query("SELECT * FROM images")); //Count number of rows

    $max = ceil($no/$limit);  //Divide it by the limit and round off to detemine the number of pages


$nav = "";    //This variable determines the pages
    for($page = 1; $page <= $max; $page++)   //Loop to get the pages
{
   if ($page == $start)
   {
      $nav .= "<span class=\"sel\"> $page </span>"; // no need to create a link if the start page == current page
   }
   else
   {
      $nav .= " <a href=\"$page_name?q=$page\">$page</a> "; //Else add the page number, here the link of <a href> is the same page passed with argument of page number ('q')

   }
}
if($start > 1){     //Above codes make a complete thing but its rather good to add these, the professional features. This add [Prev] and [First].

    $page = $start - 1;
    $prev = " <a href=\"$page_name?q=$page\">[Prev]</a> ";
    $first = " <a href=\"$page_name?q=1\" \">[First]</a> ";
}else{
    $prev  = '&nbsp;';
    $first  = '&nbsp;';
}

if($start < $max){   //This adds the [Next] and [Last] i think the code is pretty understandable.
    $page = $start +1;
    $next = " <a href=\"$page_name?q=$page\">[Next]</a> ";
    $last = " <a href=\"$page_name?q=$max\">[Last]</a> ";
}else{
    $next  = '&nbsp;';
    $last  = '&nbsp;';
}

echo "<div id=\"nav\">".$first. $prev. $nav. $next. $last."</div>";  //Now we write the navigation bar.
echo "<br />";

//Right. Heyy what about the images?? Ohh :D here it comes

    $result = mysql_query("SELECT * FROM images LIMIT $eu,$limit");
//In the above query the records are called from a specific no of records($limit) starting by a specified point($eu) ex: "SELECT * FROM images LIMIT 10,20" is thats what passed, Mysql will return records starting from the 10th records (including 10th) another 20 mean 10-39. This way page breaking is pretty simple :D



    while($rows = mysql_fetch_array($result)){
        $img = $rows['Img'];       //get the img URL
        $test = getimagesize($img); //This is optional but you may need
        $desc = "Description :" .$rows['Desc']. "<br />".
                "File Name :" .basename($img) ."<br />".
                "Diemensions :" .$test[0]. "x" .$test[1]. "<br />".
                "File Size :" .ceil(filesize($img)/1024). "KB";
                 //Above whole of it was about makign a nice description of the image.

        echo "<a href=\"".$img."\" rel=\"lightbox[gal]\" title=\"".$desc."\"><img src=\"" .$img. "\"/></a>";
               //Add the images, looping though the records
               //AURAH! php done :D
    }
   
   
   }   
}

?&gt;
Just dont run it, you see nicely sized images Big Grin
so here the CSS style

[style.css]
Code:
img{
    height:25%;
    padding:10px;
    border:2px solid #666;
    margin:5px;
   
   
}

#nav{
    left:0;
    text-align:center;
    font-family:"calibri";
    font-size:18px;
    text-decoration:none
}
#nav .sel{font-size:22px}

A:link,A:visited,A:active, A:hover { text-decoration: none; color:#333}
And add this to attach the CSS style
Add to the bottom of view.php
.....
?>
Code:
<html>
<head>
<link href="style.css" rel="stylesheet" type="text/css">
</head>
</html>
Now you'll see a pretty much good Big Grin gallery.

2) Adding lightbox
Light box is a very attrtactive feature used in many things today. In the code above you'll notice that the  tag is full of other things which of course related to the lightbox. So first Download Lightbox.
Now extract all the directory where you have the view.php but DONT extract the index.html.

Now we have to do the linking of the Lightbox.
Modify the HTML code like this:
Code:
<html>
<head>
&lt;script type="text/javascript" src="js/prototype.js"></script>
&lt;script type="text/javascript" src="js/scriptaculous.js?load=effects,builder"></script>
&lt;script type="text/javascript" src="js/lightbox.js"></script>
<link rel="stylesheet" href="css/lightbox.css" type="text/css" media="screen" />
<link href="style.css" rel="stylesheet" type="text/css">
</head>
</html>


Now you click on images and SEE A WONDER Big GrinD

3) Adding AJAX
AJAX(Asynchronous JavaScript and XML_) is an attractive technology ijmplemented by many popular sites.
ex: in facebook the images load when browsing a Gallery without loading pages seperately. This allows easy navigation to the user. Adding AJAX is pretty much simple in our case.

Make a new file called inidex.php
This is the page that user first sees
Heres the code for it

[index.php]
Code:
<html>
<head>
<title>My Gallery</title>

&lt;script type="text/javascript"&gt;
function init(){
    view(1);
}
function view(no){

xmlhttp = new XMLHttpRequest();  //Make a new XML request. It is used to send the AJAX requests.
xmlhttp.onreadystatechange=function() //This function retrieves the response from the page and shows it in the content area

  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
    document.getElementById("load_area").innerHTML=xmlhttp.responseText;
    }else{
        document.getElementById("load_area").innerHTML = "Loading please wait ....";
    }
  }
    xmlhttp.open("GET","view.php?q="+no,true); //Here the resource path is view.php we made before. But now we have to adjust the code of view.php to suit with AJAX

    xmlhttp.send();
}
      window.onload = init;  //At loading we load the 1st set of images to prevent errors
&lt;/script>

&lt;!-- the Lightbox part should be added to this --&gt;
<script type="text/javascript" src="js/prototype.js"&gt;&lt;/script>
<script type="text/javascript" src="js/scriptaculous.js?load=effects,builder"&gt;&lt;/script>
<script type="text/javascript" src="js/lightbox.js"&gt;&lt;/script>
<link rel="stylesheet" href="css/lightbox.css" type="text/css" media="screen" />
<link href="style.css" rel="stylesheet" type="text/css">

</head>
<div id="load_area">
</div>
</html>
Here's how the view.php should be edited

[view.php]
Code:
...
.
.

else
   {
      $nav .= " <a href=\"#$page\" onClick=\"view($page)\">$page</a> "; //Note that Onclick event is added to call the javascript function when the link is clicked

   }
...
..
    $prev = " <a href=\"#$page\" onClick=\"view($page)\">[Prev]</a> ";
    $first = " <a href=\"#1\" onClick=\"view(1)\">[First]</a> ";
...
.
..
     $next = " <a href=\"#$page\" onClick=\"view($page)\"&gt;[Next]</a&gt; ";
     $last = " <a href=\"#$max\" onClick=\"view($max)\"&gt;[Last]</a&gt; ";
..
..
in style.css
img{ replaced with #load_area img{

VIOLAAAAAHH!!!!!
DONE it 
You'have sucessfully made an Ajax+Lightbox+php Gallery
Alter things to make it more attractive.












 

No comments:

Post a Comment