Webocreation

Sunday, September 27, 2009

Content Management System ( CMS ) using PHP and MySQL

A Content Management System ( CMS ) is used to add, edit, and delete content on a website. For a small website, such as this, adding and deleting a page manually is fairly simple. But for a large website with lots of pages like a news website adding a page manually without a content management system can be a headache.

A CMS is meant to ease the process of adding and modifying new content to a webpage. The pages content are stored in database, not in the file server.

This tutorial will present an example of a simple content management system. You will be able to add, edit and delete articles using HTML forms.
For the database table we'll call it the news table. It consist of three columns :

  • id : The article's id
  • title : The title of an article
  • content : The article itself

Now that we have the script to add articles let's create another script to view those articles. The script is list the title of articles available in database as clickable links. The article link have the article id appended like this

http://www.php-mysql-tutorial.com/examples/cms/article1.php?id=3

One possible implementation of article1.php is presented below :
Example :
<?php
include 'library/config.php';
include 'library/opendb.php';
// if no id is specified, list the available articles
if(!isset($_GET['id']))
{
$self = $_SERVER['PHP_SELF'];
$query = "SELECT id, title FROM news ORDER BY id";
$result = mysql_query($query) or die('Error : ' . mysql_error());
// create the article list
$content = '<ol>';
while($row = mysql_fetch_array($result, MYSQL_NUM))
{
list($id, $title) = $row;
$content .= "<li><a href=\"$self?id=$id\">$title</a></li>\r\n";
}
$content .= '</ol>';
$title = 'Available Articles';
} else {
// get the article info from database
$query = "SELECT title, content FROM news WHERE id=".$_GET['id'];
$result = mysql_query($query) or die('Error : ' . mysql_error());
$row = mysql_fetch_array($result, MYSQL_ASSOC);
$title = $row['title'];
$content = $row['content'];
}
include 'library/closedb.php';
?>
// ... more code here
When article1.php is first called the $_GET['id'] variable is not set and so it will query the database for the article list and save the list in the$content variable as an ordered list. The variable $title and $content will be used later when we print the result page. Take a look at the code below :
Example :
<?php
// ... previous code
?>
<html>
<head>
<title>
<?php echo $title; ?>
</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<style type="text/css">
// ... some css here to make the page look nicer
</style>
</head>
<body>
<table width="600" border="0" align="center" cellpadding="10" cellspacing="1" bgcolor="#336699">
<tr>
<td bgcolor="#FFFFFF">
<h1 align="center"><?php echo $title; ?></h1>
<?php
echo $content;
// when displaying an article show a link
// to see the article list
if(isset($_GET['id']))
{
?>
<p>&nbsp;</p>
<p align="center"><a href="<?php echo $_SERVER['PHP_SELF']; ?>">Article List</a></p>
<?php
}
?>
</td>
</tr>
</table>
</body>
</html>
If you click on an article link the script will fetch the article's title and content from the database, save it to $title and $content variable and print the HTML file . At the bottom of the page we place a code to show the link to the article list which is the file itself without any query string ( $_SERVER['PHP_SELF'] )

With this implementation each article request involve one database query. For a heavy load website with lots of articles using the above implementation can cause a very high amount of database-request. So we need a better cms solution to reduce the load.
One feasible solution is to implement caching ( cache ) which load an article from the database only once when the article was first requested. The article is then saved to a cache directory as a regular HTML file. Subsequent request to the article will no longer involve any database request. The script just need to read the requested article from the cache directory.

Example :
<?php
include 'library/config.php';
include 'library/opendb.php';
$cacheDir = dirname(__FILE__) . '/cache/';
if (isset($_GET['id'])) {
$cacheFile = $cacheDir . '_' . $_GET['id'] . '.html';
} else {
$cacheFile = $cacheDir . 'index.html';
}
if (file_exists($cacheFile))
{
header("Content-Type: text/html");
readfile($cacheFile);
exit;
}
// ... more code coming
?>

First we need to specify the cache directory where all cache files are located. For this example the cache directory is located in the same place as the article2.php script. I mean if article2.php is stored in C:/webroot then the cache dir is in C:/webroot/cache/
The script thent check if the article was already in the cache. An article is saved into the cache directory using a filename generated from it's id. For example if you request the article using a link like this :

http://www.php-mysql-tutorial.com/examples/cms/article2.php?id=3

Then the cache file for the article is_3.html

This filename is just an underscore ( _ ) followed by the article id. In case article2.php is called like this :

http://www.php-mysql-tutorial.com/examples/cms/article2.php

no id is defined so we make the cache file name as index.html
If the cache file is found , the content is read and printed using readfile() and the script terminate. When the article is not found in the cache then we need to look in the database and get the page content from there.
Example :
<?php
// ... previous code
if(!isset($_GET['id']))
{
$self = $_SERVER['PHP_SELF'];
$query = "SELECT id, title FROM news ORDER BY id";
$result = mysql_query($query) or die('Error : ' . mysql_error());
$content = '<ol>';
while($row = mysql_fetch_array($result, MYSQL_NUM))
{
list($id, $title) = $row;
$content .= "<li><a href=\"$self?id=$id\">$title</a></li>\r\n";
}
$content .= '</ol>';
$title = 'Available Articles';
} else {
// get the article info from database
$query = "SELECT title, content FROM news WHERE id=".$_GET['id'];
$result = mysql_query($query) or die('Error : ' . mysql_error());
$row = mysql_fetch_array($result, MYSQL_ASSOC);
$title = $row['title'];
$content = $row['content'];
}
include 'library/closedb.php';
// ... still more code coming
?>
As you can see above the process of fetching the article list and content is the same as article1.php. But before showing the page we have to start output buffering so we can save the content of the generated HTML file.
See the code below. Just before printing the html we callob_start() to activate output buffering. From this point no output is sent from the script to the browser. So in the code example below anything between <html> and </html> tag is not sent to the browser but stored in an internal buffer first.
After the closing html tag we useob_get_contents() to get the buffer content and store int in a temporary variable, $buffer. We then call ob_end_flush() which stop the output buffering ( so the page is now sent to the browser ).
Example :
<?php
// ... previous code
ob_start();
?>
<html>
// ... same html code as article1.php
</html>
<?php
// get the buffer
$buffer = ob_get_contents();
// end output buffering, the buffer content
// is sent to the client
ob_end_flush();
// now we create the cache file
$fp = fopen($cacheFile, "w");
fwrite($fp, $buffer);
fclose($fp);
?>

Now that we have the file content we can write the cache file using the filename generated earlier ( using underscore plus the article id ). From now on any request to the article will no longer involve a database query. At least until the article is updated.

Tuesday, September 22, 2009

TEMPLATES in C++

TEMPLATES

Templates are one of the features added in C++ recently. It is a new concept which enable is to define generic classes and functions and thus provides supports for generic programming and provides flexible
Generic programming is an approach where generic types are used as parameters in algorithms so that they work for variety of suitable data-types and data structure.
A template can be used to create a family of classes or functions. For e.g.: a class template for an array class would enable us to create array of various data-types such ass int array and float array etc.
A template can be considered as a kind of macro when ana object of a specific type is defined for actual use, the template definition for that class is substituted with the required data type. Since a template is defined with a parameter that would be replaced by specific data type at the time of actual use of class or function, the templates are sometime also called vparameterized classes or function.
Class templates

The general format of a class template is:
Template<class T>
Class classname
{
…………
//class member specification
//with anonymous type T
//when even appropriate
……….
};

The syntax for defining an object of a template class is:
classname<type>objectname(arg_list);

#include<>m.h
Const size=3;
template<class t>
class vector
{
t *v; //type t vector
public:
vector()
{
v=new T[size];
for(int i=0;i<size;i++)
v[i]=0;
}
vector(T*a)
{
for(int i=0;i<size;i++)
v[i]=a[i];
}
T operator *(vector &y)
{
T sum=0;
for(in i=0;i<size;i++)
Sum+=this->v[i]*y.v[i];
return sum;
}
};
Void main()
{
int x[3]={1,2,3};
int y[3]={4,5,6};
vector <int> v1;
vector<int> v2;
v1=x;
v2=y;
int R=v1*v2;
cout<<”R=”<<R<<endl;
float x1[3]={1.1, 2.2,3.3};
float x2[3]={4.4,5.5,6.6};
vector<float> v3;
vector<float>v4;
v3=x1;
v4=x2;
float R1=v3*v4;
cout<<”R1=”<<R1;
}

Class template with multiple parameters:

Template <class T1, class T2>
Class classname
{
-------------------
--------------------// body of class
}

What do you mean by virtual destructor?

What do you mean by virtual destructor?
Just like ordinary virtual functions destructors can also be declared as virtual, whereas constructor cannot be Virtual. When a derived object pointed is deleted, destructors of all its base classes as well as destructor of derived classes are involved if we declare base class pointer as virtual.
But if the destructor in base class is non-virtual then only the destructor of the base class is invoked when the base class pointer pointing to the derived class object is deleted.

//Code of virtual destructor

#include<iostream.h>
#include<string.h>
class parent
{
protected:
char*name;
public:
parent (char*x)
{
name=new char[strlen(x)+1];
strcpy(name x);
}
virtual void show()
{
cout < <"parents name:" < <name;
}
virtual ~parent()
{
delete name;
cout<<"parent destroyed"<<endl;
}
};
class child:public parent
{
private:
char*name;
public:
child(char*x1,char x2):parent(x1)
{
name=new char[strlen(x2)+1];
strcpy(name,x2);
}
void show()
{
cout<<endl<<"childs name:"<<name;
}
~child()
{
delete name;
cout<<endl<<"child destroyed";
}
};
void main()
{
parent *p1;
p1=new parent("parent");
p1->show();
delete p1;
p1=new child (parent from child class:."child");
p1->parent::show();
delete p1;
getch();
}
Output
Parent name: parent
Parent destroyed
Child name: child
Parent name: parent from child class
Child destroyed
Parent destroyed

If we remove virtual keyword in the definition of destructor of base class, the second last output line (“child destroyed”) is not obtained virtual function used in following situation:

It is used when one class needs to delete object of derived class that are addresses by the base class pointer and invoked a base class destructor to release resources allocated to it.

When delete operation is performed on an object by a pointer or reference the program will first call the object destructor instead of the destructor associated with the pointer or reference type if the destructor is defined as virtual.“this” pointer

C++ uses a unique keyword called ‘this’ to represent an object that invokes a member function
This is a pointer that points to the object for which this function was called.
-for e.g. the function call A.max() will set the pointer this to the address of the object A
This unique pointer is automatically passed to a member function when it is called. The pointer ‘this ’ acts as an implicit argument to call the member functions
This pointer refers to an object that currently invokes a member functions
Syntax:
class test
{
Int data;
public:
func(){..;}
func()
{
this->data;
this->func();
}
};
Complex add(complex c2)
{
Complex t;
t.real=real+c2.real;
t.imag=imag+c2.imag;
return *this;
}

Therefore, this pointer can be used to return objects
For e.g.
#include<iostream.h>
Class person
{
Int age;
Public:
person(int a)
{age=a;}
Void disp;ay()
{Cout<<age;}
Person greater(person&);
};
Person person::greater(person &x)
{

If(age,x.age)
return x;
else
return *this;
}
void main()
{
person per(15), per(13);
person p=per.greater(pet);
cout <<”the greater age is :”;
p.display();
}

Output
The greater age is:15

Define JavaScript? List advantages and disadvantages between java and JavaScript?

Define JavaScript? List advantages and disadvantages between java and JavaScript?
JavaScript is a compact, object-based scripting language for developing client Internet applications. It was designed to add interactivity to HTML pages. JavaScript is a scripting language - a scripting language is a lightweight programming language. A JavaScript is usually embedded directly in HTML pages. JavaScript is an interpreted language (means that scripts execute without preliminary compilation).Everyone can use JavaScript without purchasing a license. All major browsers, like Netscape and Internet Explorer, support JavaScript. JavaScript was developed by Netscape as Live Script - changed to JavaScript when endorsed by Sun 1993, version 1.0 released with Netscape 2.0. JavaScript is a powerful scripting language that is also capable of performing extensive form data collecting and form processing functions.
For instance, the following is an example of a complete script JavaScript tag:

Advantages of JavaScript
• Cross Browser supporting:
This means that the JavaScript codes are supported by various browsers like Internet Explorer, Netscape Navigator, and Mozilla etc.
• Platform Independent:
JavaScript codes can be executed in any platform like Linux, Microsoft Windows and many other operating systems.
• Lightweight for fast downloading:
The JavaScript codes runs directly in the client machine. The code should be downloaded all the way from server to the client and this time duration is very minimum and the executing the codes of JavaScript is also very fast.
• Validating Data:
The data can be validated in the two different ways:
 Validating in server side or in server machine.
 Validating in client side or in client machine.
In these two different types of validation of data the second one is much more faster, and this is done through JavaScript.
• Sophisticated User Interfaces:
By
using JavaScript you can create a user interactive interfaces that can
communicate with the user and the Browser.
• In-Built software:
To you don't need any extra tools to write JavaScript, any plain text or HTML editor will do, so there's no expensive development software to buy.
• Easy to Learn:
The JavaScript programmer should know the minimal syntax of JavaScript since it supports many syntax and data types as C and C++.
It's also an easy language to learn, and there's a thriving and supportive online community of JavaScript developers and information resources.
• Designed for programming User-Events:
JavaScript supports Object/Event based programming. So the code written in JavaScript can easily be break down into sub-modules.
Disadvantages of JavaScript:
• Launching an application on the client computer.
JavaScript is not used to create stand-alone application; it is only used to add some functionality in any web page.
• Reading or writing files:
JavaScript cannot read and write files into the client machines. It can only be used as a utility language to develop any web site.
• Retrieving the text contents of HTML pages or files from the server.
• Reading and Writing files to the server:
JavaScript can read and write to any file in the server as well.
• Sending secret e-mails from Web site visitors to you:
JavaScript cannot be used to send email to the visitors or user of the web site.
This can be done only with the server side scripting.
• Cannot create Database Application:
By using JavaScript you cannot connect the web site to the database. For this you need to use server-side scripting.
• Browser Compatibility Issues:
Not all browsers support the JavaScript codes. The browser may support JavaScript as a whole, but may not support the codes or lines of codes written in JavaScript and may interpret differently.
• JavaScript does not implement multiprocessing or multithreading.
• Use printers or other devices on the user's system or the client-side LAN.
• JavaScript has limitations of writing in a client machine. It can only write the cookie in client machine that is also of a certain size i.e. 4K.

What do you understand by CSS? Write the advantages of CSS?

Cascading Style Sheets, fondly referred to as CSS, is a simple design language intended to simplify the process of making web pages presentable. Cascading Style Sheets (CSS) is a style sheet language used to describe the presentation semantics (that is, the look and formatting) of a document written in a markup language. Its most common application is to style web pages written in HTML and XHTML, but the language can be applied to any kind of XML document, including SVG and XUL.

Advantages of CSS:

Flexibility-By combining CSS with the functionality of a Content Management System, a considerable amount of flexibility can be programmed into content submission forms. This allows a contributor, who may not be familiar or able to understand or edit CSS or HTML code to select the layout of an article or other page they are submitting on-the-fly, in the same form.

Page reformatting-With a simple change of one line, a different style sheet can be used for the same page. This has advantages for accessibility, as well as providing the ability to tailor a page or site to different target devices. Furthermore, devices not able to understand the styling will still display the content

CSS saves time We can write CSS once and then reuse same sheet in multiple HTML pages. We can define a style for each HTML element and apply it to as many Web pages as we want. All styling is kept in a limited number of style sheets. The positive impact this has onsite maintenance can’t be overestimated—editing one style sheet is obviously more efficient than editing 10,000 HTML files!

Pages load faster If we are using CSS, We do not need to write HTML tag attributes every time. Just write one CSS rule of a tag and apply to all the occurrences of that tag. So less code means faster download times. The overall saving in bandwidth is measurable. Since the style sheet is cached after the first request and can be reused for every page on the site, it doesn’t have to be downloaded with each web page. Removing all presentational markups from your web pages in favor of using CSS also reduces their size and bandwidth usage—by more than 50% in many documented cases. This benefits the site owner, through lower bandwidth and storage costs, as well as the site’s visitors, for whom the web pages load faster.

Easy maintenance To make a global change, simply change the style, and all elements in all the web pages will be updated automatically. The positive impact this has onsite maintenance can’t be overestimated—editing one style sheet is obviously more efficient than editing 10,000 HTML files!

Superior styles to HTML CSS has a much wider array of attributes than HTML so we can give far better look to our HTML page in comparison of HTML attributes. The separation of content from presentation makes it easier for site owners to reuse the content for other purposes, such as RSS feeds or text-to-speech conversion.

Multiple Device Compatibility Style sheets allow content to be optimized for more than one type of device. By using the same HTML document, different versions of a website can be presented for handheld devices such as PDAs and cell phones or for printing. Separate styling rules can be used for different output media.

Global web standards –Now HTML attributes are being deprecated and it is being recommended to use CSS. So it’s a good idea to start using CSS in all the HTML pages to make them compatible to future browsers.

happy dashain jokes

Changa chet, ramailo bhet,
nidar ma tika, kan ma jamara,
khasi ko rate, masu ko plate,
Juwa ko khel,hunacha shabai ko mel
lakhou ko mal,chiurako thal..
64 saal, Dashain babbal
“Happy Dashain 2066”

Wednesday, September 9, 2009

गाउँबाट भर्खरै शहर आएका एउटा केटा पसलमा गएछ:

Dashain Special jokes and fun in Nepali
गाउँबाट भर्खरै शहर आएका एउटा केटा पसलमा गएछ:
केटा: साहुजी, यहाँ के-के पाइन्छ ?
साहुजी: यहाँ कोक, फेन्टा, पेप्सी... सबै पाइन्छ ।
केटा: त्यसोभए मलाई कोक र पेप्सी गरेर एक पाथी राख्दिनुस न ।