“How to add archive functionality to your PHP app”

“An archive refers to a collection of records, and also refers to the location in which these records are kept. Archives are made up of records which have been created during the course of an individual or organization’s life.” – Wikipedia.

Archive is an essential feature of a well defined blog system. If you have a blog in blogger or wordpress, you’ll get built-in archive feature there. But if you are making a blog yourself or any similar application, you might need to add this function yourself. These are some ideal example of archives:

Omar Al Zabir www.phpfour.com somewherein bangla blog

I’ve done it for one of my app and here I am telling you the time saving tip: creating an archive function in 3 easy steps.

1. Generate organized archive data: Generally, archives are created on create date of contents. Let’s say, your blogs table has a field named create_date which holds the timestamp of the post. Now, you can get your archive data in very organized format with this simple yet powerful query (it’s in MySQL):

SELECT COUNT(id) total, MONTHNAME(create_date) month, YEAR(create_date) year

FROM blogs

GROUP BY MONTH(create_date), YEAR(create_date)

ORDER BY create_date

Note that you’ll need to use where clauses if there are any condition. The output of your query should look like this:

Query to retrieve archive data The result
image image

 

2. Use the archive data: After you have retrieved the archive data, you can display them in any sidebar of your application. A sample code can be as follows:

 

 1: <h4>Older Entries</h4>
 2: <ul>
 3: <?php foreach ($archive as $month): ?>
 4: <li>
 5: <a href="<?php echo $month['year'] . "/" . $month['month'] ?>">
 6: <?php echo $month['month'] . " " . $month[' year'] ."(" . $month['total'] .")" ?>
 7: </a>
 8: </li>
 9: <?php endforeach; ?>
 10: </ul>

So, what’s done here? Well, it displays the archive sets with an appropriate link. Note that the link are created in “clean URL” style, i.e. yourdomain.com/2007/july – if you are using an MVC framework like CodeIgniter or CakePHP, you may find it easy to integrate. You can of course create it in the old style, by changing the above code in this way:

 1: <li>
 2: <a href="blog.php?year=<?php echo $month['year'] ?>&month=<?php echo $month['month'] ?>>
 3: <?php echo $month[''month'] . " " . $month[' year '] ."(" . $month['total'] .")" ?>
 4: </a>
 5: </li>

3. Display related posts: And now you’ll need to handle the fetching of appropriate posts based on the passed archive information (year and month), but that’s something that only you can figure out, as I don’t know what you have in there.

Happy Blogging…Happy Archiving 🙂

Hello World!

Hellow World! Now I am here…. at ajaXray.

I have been blogging on wordpress for a short time as http://php4bd.wordpress.com/. Though it’s a nice experience, I am facing some limitations there. Moreover, I have been thinking for a domain to share, test and explore my works and experience on an unique web identity. As a result, I get the domain ajaXray.

Behind the name : The name “ajaXray” comes from 2 words.

  1. ajax: AJAX, is a web development technique used for creating interactive web applications. This is the current crazes of web technologies.
  2. X-ray: X-rays (or Röntgen rays) are a form of electromagnetic radiation with a wavelength in the range of 10 to 0.01 nanometers. generally, its known to us for it’s power of scanning. I choose the word after ajax to express the interest of exploring the web technologies in such a scanning depth.

And the last thing… this domain+hosting is gifted by my (30%)boss, (30%)teacher and (40%) friend Emran Hasan aka phpfour.today is his birthday. HAPPY BIRTHDAY TO PHPFOUR.

Ajax-like Unobtrusive File Upload

We use AJAX whenever we need to communicate with the server, without reloading the page. But this doesn’t function in the case of File Upload. In usual view, uploading files with AJAX is impossible! (FireFox/Mozilla can do this after change a setting in “about:config” – which we cannot guarantee for a lot of users).

When I was searching for any technique to upload file without reloading page, I found a script in www.webtoolkit.info . But it seemed very complex to me. Then I try to simplify their technique and its working great. So I thought why not share the technique with everybody?

First, look at the demo here to see how it works.

OK. Let’s get into the deep. What happens when we submit a form? The form is submitted to the action page and that page loaded in current frame of window. If the “target” attribute of form indicate “_blank” or any frame name of the window, the page loads in a blank window or in the named frame or inner frame. Here we’ll be using the second method.

First, take an inner frame in anywhere of the page. And set the display property of this frame as “none”:

    <iframe name="hiddenFrame" id="hiddenFrame" 
    src="about:blank" style="display:none" >
    </iframe> 

Now, just set this frame as the target of your uploading form.

<form name="testForm" id="testForm" enctype="multipart/form-data" 
    action="upload.php" method="post" target="hiddenFrame">
        <input type="file" name="name" /> 
        <input type="submit" value="Upload!" />
    </form>

If we submit this form now, it will submit the file to the target script on the server (can be in php, asp etc.). The script will upload the file and will load the response in the frame “hiddenFrame”. As the frame is not visible, nothing about this loading will be seen by the visitors. Now, as the uploading page displays nothing after uploading your file, the response can be immediate. Although it’s not AJAX, this technique will upload your file without (visually) reloading page.

What more?

For many purpose, we might need a callback function when using AJAX. For this file uploading technique also, we will try to create something like that. First, we’ll write the callback function as a simple JavaScript function in the header of the uploading page:

<script language="javascript">
function trackThis()
{
var resultDiv = 
    window.frames.hiddenFrame.document.getElementById(‘result’);
var uploadedImage = document.getElementById(‘UploadedImage’);

uploadedImage.src = resultDiv.innerHTML; 
uploadedImage.style.display="block";

alert("File Uploaded :" + resultDiv.innerHTML);
}
</script>

When the uploading of the server page is complete, it should print the JavaScript code in the hidden iframe, to call the callback function with the reference “window.top”. Any other required information also can be printed in specific DIVs. It will enable us to retrieve any response information using the innerHTML of any specific DIV (as shown in example callback function).

Example:

<?php
print_r($_FILES["name"]);
if(move_uploaded_file($_FILES["name"]["tmp_name"], 
            dirname(__FILE__)."/".$_FILES[‘name’][‘name’]))
{
echo "Your uploaded file is: <div id=’result’>".$_FILES[‘name’][‘name’]." </div>";
}           
else
{
    echo "<div id=’result’>Sorry! Error occured!</div>";  
}
echo <<<test
<script type="text/javascript">
window.top.trackThis()
</script>
test;
?>

Well, that’s it. This technique has already saved my ass once, see if it can save yours also when you need.

jQuery controlled Dependent (or Cascading) Select List

When I was searching the web for a client side dependent list boxes, I got some scripts. But some of them were very much static (static select name, option name etc.), some were vary complex. Then I thought to make it myself.
I have been using jQuery as the standard JavaScript library for most of my web project for some days. Writing javascript coding in jQuery is fun. So here goes my contribution using it.

Here is a simple demo.

Let me guide you through it.

1. Include jqury.js.

<script language=”javascript” src=”jquery.js”></script>

You can get Jquery from here.

2. Write this simple function in a javascript block in head.

function makeSublist(parent,child,isSubselectOptional)
{
$(“body”).append(“<select style=’display:none’ id='”+parent+child+”‘></select>”);
$(‘#’+parent+child).html($(“#”+child+” option”));
$(‘#’+child).html(“<option> — </option>”);
$(‘#’+parent).change(
function()
{
var parentValue = $(‘#’+parent).attr(‘value’);
$(‘#’+child).html($(“#”+parent+child+” .sub_”+parentValue).clone());
if(isSubselectOptional) $(‘#’+child).prepend(“<option> — Select — </option>”);
}
);
}

This function takes 3 arguments: the parent select input’s id, the child select input’s id, and a boolean value to indicate whether to select an item from child list by default.

Example: makeSublist(‘listA’,’listB’,false);

This function will make the options of ‘listB’ list depending on the selection of ‘listA’. And user have to select an item from ‘listB’.
Here ‘listA’ and ‘listB’ are the IDs of parent and child select input respectively.

3. Add a class to the ‘<option>’s of the child list box. The class name will be the value of it’s parent ‘<option>’ in parent listbox with a ‘sub_’ prefix.
Suppose, in parent listbox there is an item “Flower”. Its value is ‘fl’:

<option value=’fl’>Flower</option>

When the item “Flower” will be selected, only 3 items should be visible in child listbox. These 3 items should hold the class name ‘sub_fl’:

<option class=”sub_fl” value=”1″>Rose</option>
<option class=”sub_fl” value=”2″>Sunflower</option>
<option class=”sub_fl” value=”3″>Orchid</option>

4. Now you are ready. On ‘$(document).ready’ event of Jquery, run the function to associate your list boxes.

$(document).ready(function()
{
makeSublist(‘parentID’,’childID’, false);
});

5. Enjoy 🙂