Showing posts with label php tutorials. Show all posts
Showing posts with label php tutorials. Show all posts

Free PHP comment script

The script can be included in your website pages and allows your visitors to leave comments. The comments can be edited and deleted in the admin area.

Comment Script Features

:: Visitors can enter a name, e-mail, homepage, comment title and comment text
:: Comment script can be included in existing web pages
:: E-Mail notification of new comments
:: Comment moderation
:: CAPTCHA feature to prevent spam
:: Akismet
:: Content Blocker
:: IP Blocker
:: Flood protection
:: Bad Word Filter
:: Smilies/Emoticons
:: Admin area for editing and deleting comments
:: Completely template driven
:: Installation routine

How the script works

Once you have the script installed on your server you can include it in any existing PHP or HTML page. By default the script shows the form fields "name", "E-mail", "Homepage", "Title", and "Comment". You are free to remove some of the fields and only leave the ones you want. The field "Comment" is mandatory and the form will not submit until that field has been filled out.

In order to prevent the script from being abused by automatic spam bots, you can enable the Captcha feature. The script then asks your visitors to enter a text they see in the image below the comment form into an input box. The comment will only be submitted if the strings match. Visitors have to ensure that their browser support and accept cookies, otherwise the comment cannot be verified.

The script also features an admin area where comments can be edited and deleted. Also there is a section for settings where you can set the front end language as well as the admin account.

Requirements

Comment Script runs on every webserver with PHP/4 or PHP/5. It needs a MySQL database on Windows, Unix or Linux operating system to function properly. You also need a software (WinZIP for example) to unpack the script files after downloading from our server. You should have a solid understanding of HTML and some experience with script installation.

Demo
comment php script

Click here to download free php comment script | More free php script

Quick Calendar Using AJAX and PHP

Online calendars are often used in many web applications. Though popular, the logic behind creating a calendar can be scary especially for those who are new to programming. There are many web calendars in the market but some of them are quite complicated. If we are not able to understand the code, it becomes harder for us to customise the calendar to fit into our existing application. As such, we need to create a calendar that can plug itself into any system seamlessly without problems. Whether we are using Wordpress, Mambo/Joomla or Drupal, we should only need to insert one line into our code for the calendar to work. ie something like this:

require_once('quick_calendar.php');
?>


If you are already bored at this point or not interested to know how to create a web calendar, feel free to see a live demo of the simple calendar here. The installation procedures is in the source code.

Other than configuring the database access for the calendar, I do not want to change other things. With AJAX, I could even make the page static as I navigate between different months in the calendar. In this tutorial, I would like to share with you a simple calendar I created that fufills the objectives discussed above. The tutorial assumes that you have basic knowledge of PHP and SQL but don't worry, the actual code is minimal and you should be able to customise it easily by reading at the comments. I used PHP 4 so that it is compatible with most servers. You should also be able to re-create the calendar easily in other programming languages using the same logic.

The First Step Problem Identification:

Perhaps the hardest part in creating a calendar is to come up with a good solution to display the days of the month in the correct column, ie Monday, Tuesday..etc.



Let us take April 2006 for example. There are 30 days and 6 rows in the calendar. If we are given a day in the month, say 15, we have to know that it falls on a saturday and is in the third row (third week). We cannot take for granted that the first day is always the first cell in the table (top left cell). Sometimes, we get 4 or 5 weeks in a month. Only if we know how many days are there in a certain month and which day the first of the month falls in only can we construct the calender as shown above.

Getting Crucial information From The PHP Date function

PHP provides a date() function that gives us alot of useful information about the days and months of the year. To built the calendar for any month, We need 2 important pieces of information from the Date function, ie the "number of days in the month" and a "numeric representation of the first day of the month".

I can get today's date easily from the following code:

// get year, eg 2006
$year = date('Y');
// get month, eg 04
$month = date('n');
// get day, eg 3
$day = date('j');


To get the number of days in this month, I will use the both the date and mktime function like so:

// get number of days in month, eg 28
$daysInMonth = date("t",mktime(0,0,0,$month,1,$year));


The numeric representation of the day of the week ranges from 0 to 6. 0 is sunday and 6 is saturday. Again, to get the numeric first day of this month, the function mktime comes in handy.

// get first day of the month, eg 4
$firstDay = date("w", mktime(0,0,0,$month,1,$year));


The Monthly Calendar As A 2-D Array

If we look at the calendar again for April 2006, we will see that it is actually a table(grid) filled with values starting from 1 to x (no of days in the month). The first day of the month is a variable though... It can occur in any day of the week. In the table, imagine each cell as having coordinates (x,y), starting from the top left cell as (0,0) and the bottom right cell as (5,6). In the month of April, the first day of the month is stored in coordinate (0,6). So, the plan now is to store the days of the month in a 2-D Array.

Firstly, we want to know the number of cells needed.

// calculate total spaces needed in array
$tempDays = $firstDay + $daysInMonth;


Then we want to know the number of rows needed.

// calculate total rows needed
$weeksInMonth = ceil($tempDays/7);


Populating The 2-D Array

Knowing the number of rows and columns in the 2-D array, we can now fill the arrays with values using 2 for-loops. The first cell will start with a value of 1 and the subsequent cells will have their values increased by 1 till it reaches the end of the array.

for($j=0;$j<$weeksInMonth;$j++) {
for($i=0;$i<7;$i++) {
$counter++;
$week[$j][$i] = $counter;
}
}
?>


For the month of April, the temporary array should be something like this:



The Magic Offset

As you can see, the array above is not correct. The first day of April, ie value 1 should be in (0,6) instead of (0,0). Remeber the variable $firstDay? It is the numeric representation of the first day of month which happens to be 6 in April 2006. If we subtract $firstDay from all the values in the array, we will get the array as follows:



You should now be able to guess what we are going to do next. Looking at the array above, you see that we already got the values we want but we also have some unwanted values. Any number less than 1 or more than $daysInMonth (number of days in a month) should be ignored.

function fillArray() {
// create a 2-d array
for($j=0;$j<$this->weeksInMonth;$j++) {
for($i=0;$i<7;$i++) {
$counter++;
$this->week[$j][$i] = $counter;
// offset the days
$this->week[$j][$i] -= $this->firstDay;
if (($this->week[$j][$i] < 1) || ($this->week[$j][$i] > $this->daysInMonth)) {
$this->week[$j][$i] = "";
}
}
}
}
?>


This is the core function in the entire calendar generation algorithm.

Displaying The Calendar

Getting the values right in the 2-D array, we are now ready to display them. Now, we will create a table and start looping again using the foreach function.
















foreach ($week as $key => $val) {
echo "";
for ($i=0;$i<7;$i++) {
echo "";
}
echo "";
}
?>
Sun Mon Tue Wed Thur Fri Sat
$date


The final display will be like this:



We now have a plain calendar.

Adding Special Dates To The Calendar

This calendar only tells you "the days of a week" at the moment and is not very useful. Most online calendar will have reminders as well. Say for example, if my birthday falls on the 4th of April, I want the number 4 in the calendar be displayed differently, possible with a hyperlink in which upon clicking on it, will perform some task like redirecting me to a certain page or displaying more information about myself in a popup windows..etc. To do that, we need to a table in the database with at least 6 columns: id, day, month, year, link, desc.

CREATE TABLE calendar (
id INT NOT NULL AUTO_INCREMENT ,
day VARCHAR( 2 ) NOT NULL ,
month VARCHAR( 2 ) NOT NULL ,
year VARCHAR( 4 ) NOT NULL ,
link VARCHAR( 255 ) NOT NULL ,
desc TEXT NOT NULL ,
PRIMARY KEY ( id )
);


We then need to insert some data into the table for testing:

VALUES (
'', '24', '*', '2006', 'http://www.sitecritic.net', 'Check your web cccount on the 24th of every month. 2006 only!'
), (
'', '5', '11', '2006', 'some_javascript_funtion', 'Olympics, remember to buy ticket from alice.'
),(
'', '2', '1', '2007', 'some_javascript_funtion', 'early 2007. Any new plans for the year?'
), (
'', '9', '*', '*', 'http://www.evolt.org', 'Remember to check updates from evolt.org every month.'
);


The * under the month or year column means every month or year.

Next, we do a query and extract the important dates for a certain month and store it in an array.

$sql = "SELECT * FROM calendar WHERE (month='$month' AND year='$year') || (month='*' AND year='$year') || (month='$month' AND year='*') || (month='*' AND year='*')";
$rs = $db->query($sql);
while ($rw = $rs->fetchRow()) {
extract($rw);
$links[] = array('day'=>$day', 'month'=>$month, 'year'=>$year, 'link'=>$link, 'desc'=>$desc);
}
?>


If we create a class to generate the calendar, we need to pass the $links array into the class like so:

$cal = &new Calendar($cArray, $today, $links, $css);
$cal->render();
?>


The $cArray is a class containing the array for the plain calendar as shown in step 6. The $today variable is today's date. The $links variable contains the important dates in this month. With the $css variable, we can decorate the calendar table and make it look nicer.

Adding AJAX Capability

To make the calendar more user friendly, we want to be able to navigate easily between the months or years without refreshing the page. Thanks to AJAX, we can now do that easily. If the user clicks on "next month" for example, we need to call the AJAX function to refresh the calendar without refreshing the page. We do that using XMLHttpRequest. This is the main code that does the trick.

http.open('get', 'quick_calendar.php?m='+m+&y='+y+'&ran='+ran_no);

After I get a response from the AJAX function, i need to update the calender. The calendar is wrapped around with the div tag called 'quickCalender'. I just need to rewrite the contents of the tag on the fly.

document.getElementById("quickCalender").innerHTML = http.responseText;

Conclusion and Future Improvements

In this tutorial, we went through the concept of how to create a web calendar using AJAX and PHP. I left the details in the code to prevent the tutorial becoming too long and indigestable. If you look at the code hard enough, you will notice that I packed alot of codes in one file. As a good programming practice, I should have broken them down into smaller parts/files. Because the objective of this project is to create a quick "plug and forget" calendar system, I did that on purpose.

Also, the object oriented approach I used in the code may not be flexible enough if I want to have different layouts for the calendar. The problem can be easily fixed by using inheritance, ie creating a superclass for the QuickCalendar class. We can then have BrownCalendar, SpecialCalendar ...etc.

Hope you enjoy reading this tutorial as much as I wrote it. The full demo can be seen here and source code is here.

source:www.evolt.org

Finding and displaying the requested record on the detail page (PHP)

After completing the master page (see Creating a URL parameter for the links (PHP)), switch to the detail page. You must find the requested record in the database and display it on the page. The procedure consists of defining a recordset to hold a single record--the record requested by the master page--and binding the recordset columns to the page.

To find and display the requested record on the detail page:

1. Switch to the detail page or create a new PHP page if the page doesn’t exist.

2. In the Bindings panel (Window > Bindings), click the Plus (+) button and select Recordset (Query) from the pop-up menu.

The simple Recordset dialog box appears. If the advanced Recordset dialog box appears instead, click Simple to switch to the simple Recordset dialog box.

3. Name the recordset, and then select a connection and the database table that will provide data to your recordset.

4. In the Columns area, select the table columns to include in the recordset.

The recordset can be identical to or different from the recordset on the master page. Usually a detail page recordset has more columns to display more detail.

If the recordsets are different, make sure the recordset on the detail page contains at least one column in common with the recordset on the master page. The common column is usually the record ID column, but it can also be the join field of related tables.

To include only some of the table’s columns in the recordset, click Selected and select the desired columns by Control-clicking (Windows) or Command-clicking (Macintosh) them in the list.

5. Complete the Filter section as follows to find and display the record specified in the URL parameter passed by the master page:

» From the first pop-up menu in the Filter area, select the column in the recordset containing values that match the value of the URL parameter passed by the master page. For example, if the URL parameter contains a record ID number, select the column containing record ID numbers. In the example discussed in the previous section, the recordset column called CODE contains the values that match the value of the URL parameter passed by the master page.

» Select the equal sign (if it is not already selected) from the pop-up menu beside the first menu.

» Select URL Parameter from the third pop-up menu.

The master page uses a URL parameter to pass information to the detail page.

» In the fourth box, enter the name of the URL parameter passed by the master page.

For example, if the URL that the master page used to open the detail page included the suffix locationDetail.php?recordID=CBR, then enter recordID.

The Recordset dialog box should look as follows:

recordset

6. Click OK.
The recordset appears in the Bindings panel.

7. Bind the recordset columns to the detail page by selecting the columns in the Bindings panel (Window > Bindings) and dragging them onto the page.

The PHP master/detail page set is done.

Creating a URL parameter for the links (PHP)

The links in the dynamic table on the master page (see Creating the links to the detail page (PHP)) not only have to open the detail page, they must pass the ID of the record the user selected. The detail page will use this ID to find the requested record in the database and display it.

The record ID is passed to the detail page in a URL parameter.

This section describes how to create a URL parameter that passes a record ID to the detail page.

To create the URL parameter:

1. Select the link in the dynamic table.

If Live Data is turned on, select the link in the first row.

2. In the Link field in the Property inspector, add the following string at the end of the URL: ?recordID=
The question mark tells the server that what follows is one or more URL parameters. The word recordID is the name of the URL parameter (you can use any name you like). Make a note of the name of the URL parameter because you’ll use it in the detail page later.

The expression after the equal sign is the value of the parameter. In this case, the value is generated by a PHP expression that returns a record ID from the recordset. A different ID is generated for each row in the dynamic table. In the PHP expression, replace recordsetName with the name of your recordset, and replace fieldName with the name of the field in your recordset that uniquely identifies each record. In most cases, the field will consist of a record ID number. In the following example, the field consists of unique location codes.

locationDetail.php?recordID=
When the page runs, the values of the recordset’s CODE field are inserted in the corresponding rows in the dynamic table. For example, if the Canberra, Australia, rental location has the code CBR, then the following URL will be used in the Canberra row in the dynamic table:

locationDetail.php?recordID=CBR

3. Save the page.

Creating the links to the detail page (PHP)

This post describes how to create the links. The next section describes how to modify the link so that it also passes the ID of the record the user selects. The detail page will use this ID to find the requested record in the database and display it.

To create links to the detail page:

1. In the dynamic table, select the dynamic content placeholder for the text you want to be linked.

In the following example, the {rsLocations.LOCATION_NAME} placeholder is selected. The links will be applied to the location names in the column.



2. In the Property inspector, click the folder icon beside the Link field.

3. Browse and select the detail page.

The detail page appears in the Link field.

In the dynamic table, the placeholder for the dynamic content appears linked. If you run the page on a server, you can see that the link is applied to the text in every table row.

Creating the master page (PHP)

This post describes how to create a master page that lists database records. You can use a dynamic table to list the records on a PHP page.

Before you start, make sure you define a database connection for the site.

To create a master page:

1. In Dreamweaver, create a new PHP page.

Select File > New > Dynamic, select PHP, and click Create.

A blank PHP page opens in Dreamweaver.

2. Define a recordset for the page.

In the Bindings panel (Window > Bindings), click the Plus (+) button, select Recordset (Query), and complete the Recordset dialog box. For more information, click the Help button on the dialog box. If you want to write your own SQL statement, click the Advanced button to open the advanced Recordset dialog box.

Make sure the recordset contains all the table columns you need to create your dynamic table. The recordset must also include the table column containing the unique key of each record--that is, the record ID column. In the following example, the CODE column contains information that uniquely identifies each record.

recordsed

Typically, the recordset on the master page extracts a few columns from a database table while the recordset on the detail page extracts more columns from the same table to provide the extra detail.

The recordset can be defined by the user at runtime.

3. Insert a dynamic table to display the records on the page.

Place the insertion point where you want the dynamic table to appear on the page, and select Insert > Application Objects > Dynamic Data > Dynamic Table.

The Dynamic Table dialog box appears.

dynamic table

4. Complete the Dynamic Table dialog box and click OK.

Dreamweaver inserts a dynamic table on the page.

If you need help completing the Dynamic Table dialog box, click the Help button on the dialog box.

5. If you want, delete the dynamic table column containing the record IDs.

If you don’t want to show record IDs to users, you can delete the column from the dynamic table. Click anywhere on the page to move the focus to the page. Move the pointer near the top of the column in the dynamic table until the column cells are outlined in red, then click to select the table column. Press Delete to delete the column from the table.