Saturday, June 12, 2010

How to create a comments page?

Page navigation using PHP


In this post i will explain how to write a comments page with page navigation like first page, next page, previous page and last page links. You can use the same logic to write any kind of page, article, blog etc. This article assumes you have basic understanding of PHP and MySql.

Writing comments/suggestions in a blog is a common thing. With PHP and MySql it is the easier too. A simple comment page would require a comment field, a name field and email field. A captcha is optional but it is strongly recommended that you use captcha to prevent automated entries by bots.

Ok. First write html tags to design entry form. The form would consist of a textarea field to capture multilines of text. Two text fields one for name and another for email. Here is the code for the form

I have commented the html code to prevent browser from displaying the controls instead of the code. Now when the enters data and click the submit button the php code will work. The if($_POST) will check whether a post back (submit) is done. If so the code will connect mysql server and open default database and insert a row of data. Ok. I forgot the script to create a mysql table, here is the sql script to create 'comments' table,

CREATE TABLE comments (
  `ID` int(11) NOT NULL auto_increment,
  `comment_date` DATETIME NOT NULL,
  `comment` varchar(5000) NOT NULL,
  `comment_by` varchar(55) default NULL,
  `email` varchar(50) default NULL,
  PRIMARY KEY  (`ID`)
);

Below is the php code that is used to insert data into mysql table ('comments')
include 'header.html';

if ($_POST)
{

$link = mysql_connect("localhost", "root", "myuniverse"); //replace with your mysql server details.
if (!$link)
    {
            die('Not connected : ' . mysql_error());
    }
$db_selected = mysql_select_db("test", $link); //replace with your mysql database name
if (!$db_selected)
    {
            die ('Error: ' . mysql_error());
    }
$comment=$_POST["comment"];
$comment_by=$_POST["comment_by"];
$email=$_POST["email"];
if ($comment=="")
{
echo 'Empty comments are not accepted!';

}
else
{
$qry="INSERT INTO comments (comment_date,comment,comment_by,email) VALUES (curdate(),
'$comment','$comment_by','$email')";
$result = mysql_query($qry);
if ($result)
{
echo 'You comment was added successfully. Thank You';
}
else
{
echo 'Error: '. mysql_error();
}
}
}
?>

Now, we have inserted the code. We need to display the data. It is certain that we should not display all the comments on the same page. If your website gets older the number of comments will grow and displaying it on a single page is not a good idea. So we split up the data and display a small amount of comments on a page. The user can click the Next, Previous links to navigate the comments page. For this purpose we need to count the number of rows in the comments table and divide it by number of rows per page. We can set this value to a constant. For example 10,20,30 or something you want. The following code will do the same. It will determine the total pages and current page and create Next Page, Previous page, Last page links with parameter (page no). Here is the piece of code to display comments,

$link = mysql_connect("localhost", "root", "myuniverse");
if (!$link)
    {
            die('Not connected : ' . mysql_error());
    }
$db_selected = mysql_select_db("test", $link);
if (!$db_selected)
    {
            die ('Error: ' . mysql_error());
    }
$result = mysql_query("SELECT comment,comment_by from comments ORDER BY comment_date DESC");
echo '

Read Comments

';
$tot_rows=mysql_num_rows($result);
if (isset($_GET["pageno"]))
$pageno=$_GET["pageno"];
else
$pageno=1;
$rowsperpage=10;
$currow=($pageno-1)*$rowsperpage;
if ($tot_rows>0)
mysql_data_seek($result,$currow);
$cnt=0;
$totalpages=ceil($tot_rows/$rowsperpage);

while ($row = mysql_fetch_assoc($result))
{
echo '
';
echo ''.$row["comment"].'
';
echo $row["comment_by"];
echo '
';
$cnt=$cnt+1;
if ($cnt>=$rowsperpage)
break;
}

echo '
';
$next=$pageno+1;
$previous=$pageno-1;
echo 'Total comments: '.$tot_rows;
echo '
';
if ($pageno>1)
echo 'First page ';
if ($pageno<$totalpages)
echo 'Next page > ';
if ($pageno>1)
echo ' Previous page ';
if ($pageno<$totalpages)echo 'Last page';
include 'footer.html';
?>
Replace the mysql server name, user name and password to your own server name, username password in mysql_connect function. Also change the database name in mysql_select_db() function. I have used include 'header.html' and include 'footer.html'. You should create your own header and footer files that display header and footer of your website. Otherwise remove those lines.

Here is the complete code:

Save the file to comments.php or something else and run! The output should look as below. Note: I have used style sheets for my header.html so the colors vary.

Wednesday, June 9, 2010

How to create a login page?

Login script tutorial, sample code

The entry point of any e-commerce website, membership portals and any login based web applications is a login page with user name and password. This is required for websites offering paid products/digital content/services/music and video content. Here is the tutorial for creating a login page using PHP and MySql database.

This tutorial assumes you have basic understanding of PHP and MySql. A membership login requires a registration page, a database table to store member / user details. A login page and script to validate login. The registration page will store member/user data in MySql database table. So first we need to create a table. I have provided the sql script below.

CREATE TABLE `members` (
  `ID` int(11) NOT NULL auto_increment,
  `Username` varchar(255) NOT NULL,
  `Password` varchar(255) NOT NULL,
  PRIMARY KEY  (`ID`),
  UNIQUE KEY `Username` (`Username`)
) ENGINE=MyISAM;

I have used the minimum number of fields to make it simple. We can write a complicated script that will send a verification email to user. Upon the user clicking activate link, his account will be activated. This is a complex script and will require more fields in the table. I will explain in future.

You save the script in a text file and execute it MySql command Window. For example, if you save the script as c:\db.sql in my sql command prompt type \. c:\db.sql This will execute whatever sql code in the file.

After the table is created create a registration page. Name it register.php. Write the following code.
//******* start of register.php
$DB_Server="localhost"; //database server
$DB_User="root"; ///mysql username
$DB_Password=""; //set mysql password
$DB_Database="test"; //database name
if ($_POST)
{
$user=trim($_POST['username']);
$passwd=trim($_POST['password']);
$email=trim($_POST['email']);

if ($user=="" | $passwd=="")
{   
    echo 'Please provide valid user name and password! Thank you';   
    exit();
}

$link = mysql_connect($DB_Server, $DB_User, $DB_Password);
if (!$link) {
    die('Not connected : ' . mysql_error());
}

// make foo the current db
$db_selected = mysql_select_db($DB_Database, $link);
if (!$db_selected) {
    die ('Error: ' . mysql_error());
}

//Create INSERT query
    $qry = "INSERT INTO members(username, password, email) VALUES('$user','$passwd','$email')";
    echo $qry;
    $result = mysql_query($qry);
    //Check whether the query was successful or not
    if($result)
    {

    echo 'You have been registered successfully. Please Login';

    }
    else
    {
        echo 'Error: ' . mysql_error();
        echo '
Registration failed. Try again';
    }

exit();
}
?>





User Name
Password
//**** End of register.php
The above file will check whether it is post back (by user submitting the form using submit button) using if ($_POST). It will return true if post back. otherwise it will display a form for user entering registration data like user name and password. If post back it will open MySql using mysql_connect() function. The parameters for this function are Servername, userid, password. You have to set these variable at the beginning of the file. The next function mysql_select_db() will select the current database to use. $result = mysql_query($qry); will execute the $qry and store the result set in $result. By checking this true or false we can be sure whether the query was success or not. This is all about the simple registration. The script will check for simple validation of blank user name and blank password.

The next thing is the login page. I have put the code below. Explanation will follow.
//********* login.php

if ($_POST)
{
$DB_Server="localhost";
$DB_User="root";
$DB_Password="myuniverse";
$DB_Database="test";

$link = mysql_connect($DB_Server, $DB_User, $DB_Password);
if (!$link) {
    die('Not connected : ' . mysql_error());
}

// make foo the current db
$db_selected = mysql_select_db($DB_Database, $link);
if (!$db_selected) {
    die ('Error: ' . mysql_error());
}
$user=trim($_POST['username']);
$pass=trim($_POST['password']);

$result = mysql_query("SELECT id, username, password FROM members WHERE username='$user' AND password='$pass'");
if (!$result) {
    die ('Error: ' . mysql_error());
}
$num = mysql_num_rows($result);
if ( $num > 0 )
{
session_start();
$member = mysql_fetch_assoc($result);
$_SESSION['SES_member_id']=$member['id'];
$_SESSION['SES_member_name']=$member['username'];
echo 'Login success';
}
else
{

echo 'userid/password is invalid.try again';

}

exit();
}

?>

Login



User Name
Password


//********* End of login.phpWhen the form is submitted by the user by clicking submit button, the form variables will be posted back to the server. We verify it using if ($_POST). Then we will open connection to the database and check whether the given user name and password is available in the database table. If available we will create new session by calling session_start() function.


session_start() creates a session or resumes the current one based on the current session id that's being passed via a request, such as GET, POST, or a cookie. After calling session_start() session variables are available to us. We can store the user name in a session variable. Now the user is logged in to the server. Whenever we want to check user login status we check the session variable with isset() function.We stored the session variable by using $_SESSION['SES_member_name']=$member['username'];

We can check the status by isset($_SESSION['SES_member_name']). We can further enhance the script by using md5 hash for passwords. Storing plain passwords is a security vulnerability and should not be done. The function md5() Returns the hash as a 32-character hexadecimal number. Use this function before storing passwords in database. We can use email activation of accounts. This way we can verify the email of users. To avoid automatic registrations you can use captcha. recaptcha is free to use captcha that will require visual verification of alphanumeric characters. You can use this in your registration pages to avoid automated bulk registrations. You can use cookies to remember a user session. You can use Php SetCookie() function to store a cookie in user's computer browser. You can check for the presence of cookie and automatically log user in. If you have questions feel free to mail me: sundaracm@gmail.com

Monday, June 7, 2010

Install PHP 5.3, MySQL, IIS On Windows XP

How to install PHP on Windows XP? Step-by-step guide


PHP gained popularity over the years. Because of its simplicity, cross-platform, open source, free availability it is now the leading server application platform available today. PHP is available in many flavors. People feel PHP installation is complicated and tough. That is a wrong opinion. PHP is fun to learn and powerful enough to build enterprise web solutions. PHP combined with MySql is an excellent platform for web applications. How to install PHP on Windows XP computer? How to setup MySQL database server on Windows XP? Which web server is best? IIS or Apache? The questions are endless. For a PHP beginner i will guide teach the each way to setup PHP.

What do i need to have?

This installation guide is to install PHP and MySQL on Windows XP Professional computer with IIS (Internet Information Server) as webserver. So you need PHP version 5.0. You can download the latest PHP version from http://php.net/downloads.php . Warning: Don't download Installer. Only download ZIP file. You need MySQL Server. MySql community server is available for free. The installation is simple and straight forward. What else? The IIS server is bundled with Windows XP CD.

 The Installation

IIS

First Install the IIS server. To do this go to control panel -> Add/Remove Programs in your windows XP Computer. Click Add Remove Windows Components button. Windows components Wizard Dialog box will open. Tick the checkbox prior to Internet Information Services. It will take approximately 13 MB of your disk space. Click next. You will be prompted to insert your Windows XP CD-ROM. Insert it. Click Next. Thats it. By Default IIS folders are located at c:\inetpub\wwwroot. make a note of it

PHP

Now extract the zip file you have downloaded to C: drive or D:\ drive or whatever drive you wish. Rename the folder something like php5. So the path should be c:\php5 or d:\php5. Open the folder. Find the file named "php.ini-development" and rename it to "php.ini". Open this file in notepad and make the following changes.

Find ;doc_root = and change it to doc_root="c:\inetpub\wwwroot"
Find ;extension=php_mysql.dll and change it to extension=php_mysql.dll  (just remove ;)
Find ;cgi.force_redirect = 1 and change it to cgi.force_redirect = 0. This is must

Now save the file and close.



Next right click my computer icon on the desktop and click properties. The System properties Dialog box will appear.

Click Environment variables. In the System Variable find a variable named path and select it. Click Edit. You will be prompted for Variable Name and Variable Value. In Variable Value Text box go the end of the line. append c:\php5. Click ok. Click ok. This sets the path Environment variable for php. You don't have to put php.ini file in Windows System Directory. PHP can now find the ini file using the path variable.

Install MySql

Installation of MySql Database server is simple and straight forward. Just double click the MySql Installer and it will do the rest. Don't select advanced setup. In the end you will be asked for MySql root password. Give a password that you can remember.

Configure IIS

There are two ways to setup php on IIS. One is CGI executable and other is ISAPI server module. We will opt for CGI. We have configure the php.ini file for CGI. Go to control panel -> Administrative Tools -> Internet Information Services. Open Default website node. Put your php script directory in c:\inetpub\wwwroot. For example c:\inetpub\wwwroot\testphp. Don't keep the directory anywhere else. IIS 5 will throw exception. The browser will give file not found exception. In the default websites your folder is shown as virtual directory. Right click it and open properties.
Under Directory Tab click create. IIS Will assign Default Application Name, Set Execute permission to Scripts only. Click Configuration. The application configuration dialogbox will appear.

Under Mapping Click Add. Click Browse. Go to your php5 directory. Select php-cgi.exe click open. In the extension give .php. Click ok Apply ok.

Now test your php installation. Open a Notepad type the follwing,
Hello World
'; ?> Save as test.php Save AS Type: All Files. Save the file at location c:\inetpub\wwwroot\testphp\


Now open your web browser Internet Explorer or Mozilla firefox. In the address bar type http://localhost/testphp/test.php and press enter. Php will output the Hello world.
That is the simple installation procedure of php 5 on windows XP and IIS.

Thursday, January 28, 2010

getElementById

Firefox doesnot recognize "name" attribute

This is to expose how Internet Explorer and Firefox browsers treat the getElementById method. This method takes the id of the field (normally the 'INPUT' field) as paramenter. If you give the id using id attribute it will work in both Internet explorer and Mozilla firefox. If you use 'name' attribute to give name to your input field/tag it won't be recognized by Firefox and your JavaScript won't work with getElementById.


Here is the example code: This will work in both IE and FireFox
Type something



In the above example i use a text filed and set its id property to 'YourName". I used a button and called a simple JavaScript function in it OnClick event to display the text in the textbox. I used the alert function to display the message box. This will work both in IE and Firefox. In the below example i set the name attribute to 'YourNameIE'. Note, i used 'name' attribute instead of 'id' attribute. That is the difference. This won't work in Firefox when you click the Click me button. That's it. So don't use name attribute in field naming.

This will work only in Internet Explorer
Type something

Tuesday, January 19, 2010

PHP Introduction - The birth

Welcome to PHP


Welcome to this free PHP tutorial blog. You have made the right decision by start learning PHP. PHP (Hyper Text Pre-Processor) is the open source server side scripting language. PHP is used to build rich and powerful web applications and database driven web sites. You can develop online shopping portals, forums, business websites, chat applications and much more with the help of PHP. Here is the brief history of birth and growth of PHP.

The history of PHP dates back to 1995, when an independent software development contractor named Rasmus Lerdorf developed a Perl/CGI script that enabled him to know how many visitors were reading his online resume. His script performed two taks; logging visitor information, and displaying the count of visitors to the web site. In those times such scripts were not available. Rasmus start receiving emails asking for the script. He started giving away his new tool, named Personal Home Page or PHP.

With his PHP gaining popularity Lerdorf began developing his PHP. Ongoing additions to the PHP toolset culminated in November 1997 with the release of PHP 2.0, or Personal Home Page - From Interpreter (PHP-FI). Programmers worldwide participated in developing PHP and adding new features to it.

In the year 1998 PHP version 3.0 was released. By then over 50000 users were using PHP to enhance their web pages. By then PHP abbreviation changed to Hypertext Preprocessor.

By 1999 more than a million people were using PHP. Two core developers, Zeev Suraski and Andi Gutmans, took the initiative to spearhead a complete rethinking of the way PHP operated, resulted in rewriting of the PHP parser from the scratch. The result of this work was the release of PHP version 4.0