Permanent (301) and Temporary (302) Redirection Using PHP

Redirection is the method of forwarding users to a new domain or URL when they
try to reach the old one.


Suppose my friend Ralph had once created a website at:


ralphhaynes.com


and after sometime created yet another website on the sub domain:


blog.ralphhaynes.com


Now he wants to have his blog (second website) on a new separate domain name.
Since he already has lots of readers who visit the old URL, he has to find some
way to let them know the new URL. The easiest way yet the most effective would
be to use Redirection.


Actually, there are two types of redirection, permanent and temporary. In the
above case when Ralph wanted to permanently move to a new domain he should use
Permanent Redirection. In some other cases when webmasters have to move from,
say a domain to a sub domain due to some temporary problems they could use Temporary
Redirection.


301 Permanent Redirection


‘301’ here is the HTTP response code sent by the server to the
client. Server sends HTTP codes for each request received from the client. These
codes reflect the type of response received from the server. Some other codes
sent are 200(OK), 404 (Not Found), 50x (Sever Problems etc.


When redirected in this manner many web applications such as browsers (Bookmarks
actually), Search Engines etc. Update their data to have the new domain instead
of the old one. Thus Permanent Redirection is also a way to tell these application
especially Search Engines that a particular site has moved to a new address.


The following PHP code can be used to do this:



<?php

// 301 Permanent Redirection Using PHP Script

header("HTTP/1.1 301 Moved Permanently");

header("Location: http://example.com/");



exit;

?>


Put this script as ‘index.php’ on the root of the old domain. Be
sure to change ‘http://example.com/’ to whatever you’d like
to redirect to.


302 Temporary Redirection


First off, Temporary doesn’t mean that the redirection would stop automatically
or anything; in fact you can use a Temporary Redirection forever, it just means
that you plan to redirect for a short period of time and therefore browsers
and Search Engines do not need to make any changes to their data.


Use the following code to achieve this:


<?php

// 302 Temporary Redirection Using PHP Script


header("Location: http://example.com/");




exit;

?>



Again don’t forget to change ‘http://example.com/’.


One thing to note here is, there is no difference in how user would get redirected
in the two types of redirections. In both the cases user will reach the new
URL, difference is for how long you’ve planned to do so. If you’ve
permanently moved to a new URL and use 301 redirection, address in browsers,
search engines etc. will change and eventually there would be no trace of the
old URL.


Previous Articles:


New Working Method of Making Blogger Title Tags SEO Friendly

New Working Method of Making Blogger Title Tags SEO Friendly


[Blogger made some recent changes on 9th May 2008 which
enables us to use a simple method to make SEO Friendly Title Tags for Post Pages
(Permalink Pages), I guess I am a bit too late to notice but as we’re
discussing about Web Programming lately, I’ll share the method anyway.]


One of the biggest problems I face with Blogger blogs is the inability to create
custom SEO and human friendly title tags. Blogger does not give us any option
to change the way title tags are in post pages. Titles of post pages in Blogger
are always in the following form:


[Blog Title] : [Post Title]


In this case when you have a bit long Blog Name, all your pages in the Search
Engine index would start with the blog name taking most of the previous space.
That way it wouldn’t be relevant to the content of the post in most cases


The following form of title would be considered good:


[Post Title] : [Blog Title]


Or if your blog’s name is too long you can use just the title:


[Post Title]


People have always been trying to come up with ways to create custom title
tags in Blogger, some used a hack few months back known as the Widget Based
Title Tag hack which NO longer works from quite some time. Even I used that
method here on my blog. But, as I said, after sometime Blogger wouldn’t
let that hack work. Again some people found a slightly different method that
WORKED but pissed off the HTML compliance really bad as title tag was placed
outside of the <head> tag. So the fact is before 9th May there really
was no way you could have custom titles and those who already had the hack working,
couldn’t edit the Template code anymore without switching back to the
normal title structure.


The Method


Below I’m outlining a very simple and 100% working way of having custom
titles in Blogger:


<b:if cond='data:blog.pageType == &quot;item&quot;'>

<title><data:blog.pageName/> | <data:blog.title/></title>

<b:else/>

<title><data:blog.pageTitle/></title>

</b:if>


Copy and paste the above code replacing the <data:blog.pageTitle/>
line in your template code.


Or if you want the posts to have just the post title in the title tag and NO
blog name or if your blog name is too long, you may use the following code,
again replace <data:blog.pageTitle/> line with this code.


[Go to Layout->Edit HTML to place these codes.]


NOTE: Titles of pages are very critical when it comes
to Search Engines not just from SEO point of view but also from human perspective.
It’s a known fact that even if your website ranks higher but has irrelevant
(same looking titles) for all the pages, chances are peoples would rather click
on lower ranking pages having relevant titles.

Creating a Simple Poll Script in PHP


OK, so again a useful script that we are going to create here. A polling system/script
needs no introduction as it has been on the Web since long and is a good method
to increase visitor activity on a website, apart from knowing their responses.


OK let’s start!


A polling system requires vote data to be stored, for that database (MySQL)
would be the best choice.


Possible table structure for the database for a poll having three options would
be



Logically thinking we know that only one row is required for a poll. Each time
someone votes the value of the respective fields should be updated (incremented).


Initially the table would be like below:


Initial values in the table



After five votes to the first option, four to the second option and one to
the third; the table would look like:


Values in the DB table after some votes




It should now be clear why we only need one row for a poll.


Designing the Poll


OK, now we’ll have to design the poll using an HTML table, some radio
buttons and a submit button. You may write your poll question and the options
besides the radio buttons. We’ll now have to integrate this to the script.


A sample Poll created by me:


A sample poll craeted by me


[NOTE: Radio boxes gives us the ability to let the visitor select ONLY ONE
option from many.]



The Script


We are going to create the script such that it shows the Poll (HTML form) when
no $_GET data is being passed, in other words visitor is requesting the Poll.
It acts accordingly when someone is tries to see the results or vote their choice.
After successful voting the result page is shown.


Here is the completed script:



<html>

<head>

<title>Polling System</title>

</head>



<body>

<h1>My Poll</h1>

<?php

//connect to MySQL 

//provide your 'USERNAME' and 'PASSWORD' 

//change 'localhost' to the MySQL server 

//host, if MySQL is on a sepearte server 

$db=new mysqli('localhost','-USER-','-PASS-');



//if this is the first time

//and database is not craeted

if(!$db->select_db('one'))

    
//create the database

    
$db->query('create database one');

    

//select the databasw to work with

$db->select_db('one');

        

//if table is not created, create it

if(!$db->query('select * from poll'))

{    

    
//create a table for a Poll having three options

    
$db->query('create table poll (id int auto_increment primary key, option1 int, option2 int, option3 int)');

    
//create an initail row with value of 0 to each field

    
$db->query("insert into poll (option1, option2, option3) values (0,0,0)");

}



//someone is trying to vote

if($_GET['action']=='Vote')

{

    
$option1=$_GET['option1'];

    
$option2=$_GET['option2'];

    
$option3=$_GET['option3'];

    
//--you may add more if needed

    //be sure to add same no. of radio buttons 

    //on the form too.

    

    //if any option was selected, then only save the vote

    
if($option1!='' || $option2!='' || $option3!='')

    {

        
//fetch initial values of polls in DB

        
$result=$db->query("select * from poll");



        
$result=$result->fetch_row();

        
$op1=$result[1];

        
$op2=$result[2];

        
$op3=$result[3];

    

        

        
//increment the voted option

        
if($option1=='voted'$op1++;

        elseif(
$option2=='voted'$op2++;

        elseif(
$option3=='voted'$op3++;

        

        
//save the updated values

        
$db->query("update poll set option1='$op1', option2='$op2', option3='$op3'");

        

        
//redirect to results page

        //by setting the $_GET var

        
$_GET['action']='Results';

    }

}

if(
$_GET['action']=='Results')

{

    
//fetch initial values of polls in DB

    
$result=$db->query("select * from poll");



    
$result=$result->fetch_row();

    
$op1=$result[1];

    
$op2=$result[2];

    
$op3=$result[3];

        

    
//close DB

    
$db->close();

//using HTML with embedded PHP for ease

?>    

    <h3>Poll Results</h3>

    <p>How does it feel to be able to vote to your own Script?</p>

     <p>Very Good!: <?php echo $op1?></p>

     <p>Not Bad...: <?php echo $op2?></p>

     <p> Bad...: <?php echo $op3?></p>



<?php

//closing of PHP blocks may be done this way

}

else

{
//show poll form

?>

    <h3>Cast Your Vote</h3>

    <form name="form1" id="form1" method="get" action="">

      <p>How does it feel to be able to vote to your own Script?</p>

      <p> 

    <input type="radio" name="option1" value="voted" />

        Very Good!</p>

      <p> 

        <input type="radio" name="option2" value="voted" />

        Not Bad...</p>

      <p> 

        <input type="radio" name="option3" value="voted" />

        Bad...</p>

      <p>

        <input name="action" type="submit" id="action" value="Vote" />

      </p>

    </form>

    <p><a href="?action=Results">Show Results</a></p>

    </body>

    </html>

<?php

}

?>


Previous Articles:


Parallel data processing language for Map/Reduce

In my previous post, I introduce Map/Reduce model as a powerful model for parallelism. However, although Map/Reduce is simple, powerful and provide a good opportunity to parallelize algorithm, it is based on a rigid procedural structure that require injection of custom user code and therefore it not easy to understand the big picture from a high level. You need to drill into the implementation code of the map and reduce function in order to figure out what is going on.

It will be desirable to have a higher level declarative language that describe the parallel data processing model. This is similar to the idea of SQL query where the user specify the "what" and leave the "how" to the underlying processing engine. In this post, we will explore the possibility of such a declarative language. We will start from the Map/Reduce model and see how it can be generalized into a "Parallel data processing model".

Lets revisit Map/Reduce in a more abstract sense.

The Map/Reduce processing model composes of the following steps ...
  • From many distributed data store, InputReader extract out data tuples A = <a1,a2,...> and feed them randomly into the many Map tasks.
  • For each tuple A, the Map task emit zero to many tuples A'
  • The output A' will be sorted by its key, A' with the same key will reach the same Reduce task
  • The Reduce task aggregate over the group of tuples A' (of the same key) and then turn them into a tuple B = reduce(array<A'>)
  • The OutputWriter store the data tuple B into the distributed data store.
Paralleizing more sophisticated algorithm typically involve multiple phases of Map/Reduce phases, each phase may have a different Map task and Reduce task.


Looking at the abstract Map/Reduce model, there are some similarities with the SQL query model. We can express the above Map/Reduce model using a SQL-like query language.

INSERT INTO A FROM InputReader("dfs:/data/myInput")

INSERT INTO A'
SELECT flatten(map(*)) FROM A

INSERT INTO B
SELECT reduce(*) FROM A' GROUP BY A'.key

INSERT INTO "dfs:/data/myOutput" FROM B

Similarly, SQL queries can also be expressed by different forms of map() and reduce() functions. Lets look at a couple typical SQL query examples.

Simple Query
SELECT a1, a2 FROM A
WHERE a3 > 5 AND a4 < 6

Here is the corresponding Map and Reduce function
def map(tuple)
/* tuple is implemented as a map, key by attribute name */
if (tuple["a3"] > 5 && tuple["a4"] < 6)
key = random()
emit key, "a1" => tuple["a1"], "a2" => tuple["a2"]
end
end

def reduce(tuples)
tuples.each do |tuple|
store tuple
end
end

Query with Grouping
SELECT sum(a1), avg(a2) FROM A
GROUP BY a3, a4
HAVING count() < 10

Here is the coresponding Map and Reduce function
def map(tuple)
key = [tuple["a3"], tuple["a4"]]
emit key, "a1" => tuple["a1"], "a2" => tuple["a2"]
end

def reduce(tuples)
sums = {"a1" => 0, "a2" => 0}
count = 0

tuples.each do |tuple|
count += 1
sums.each_key do |attr|
sums[attr] += tuple[attr]
end
end

if count < 10
/* omit denominator check for simplcity */
store {"type" => B, "b1" => sums["a1"], "b2" => sums["a2"] / count}
end
end

Query with Join
SELECT a2, p2
FROM A JOIN P
ON A.a1 = P.p1
Here is the corresponding Map and Reduce function
def map(tuple)
if (tuple["type"] == A)
key = tuple["a1"]
emit key, "a2" => tuple["a2"]
elsif (tuple["type"] == P)
key = tuple["p1"]
emit key, "p2" => tuple["p2"]
end
end

def reduce(tuples)
all_A_tuples = []
all_P_tuples = []

tuples.each do |tuple|
if (tuple["type"] == A)
all_A_tuples.add(tuple)
all_P_tuples.each do |p_tuple|
joined_tuple = p_tuple.merge(tuple)
joined_tuple["type"] = B
store joined_tuple
end
elsif (tuple["type"] == P)
/* do similar things */
end
end
end

As you can see, transforming a SQL query to Map/Reduce function is pretty straightforward.

We put the following logic inside the map() function
  • Select columns that appears in the SELECT clause
  • Evaluate the WHERE clause and filter out tuples that doesn't match the condition
  • Compute the key for the JOIN clause or the GROUP clause
  • Emit the tuple

On the other hand, we put the following logic inside the reduce() function
  • Compute the aggregate value of the columns appears in the SELECT clause
  • Evaluate the HAVING clause and filter things out
  • Compute the cartesian product of the JOIN clause
  • Store the final tuple
As we've seen the potential opportunity to use a "SQL-like" declarative language to express the parallel data processing and use a Map/Reduce model to execute it, the open source Hadoop community is working on a project call Pig to develop such a language.

PIG is similar to SQL in the following way.
  • PIG's tuple is same as SQL record, containing multiple fields
  • PIG has define its own set
  • Like SQL optimizer which compiles the query into an execution plan, PIG compiler compiles its query into a Map/Reduce task.

However, there are a number of important difference between PIG (in its current form) and the SQL language.
  • While fields within a SQL record must be atomic (contain one single value), fields within a PIG tuple can be multi-valued, e.g. a collection of another PIG tuples, or a map with key be an atomic data and value be anything
  • Unlike relational model where each DB record must have a unique combination of data fields, PIG tuple doesn't require uniqueness.
  • Unlike SQL query where the input data need to be physically loaded into the DB tables, PIG extract the data from its original data sources directly during execution.
  • PIG is lazily executed. It use a backtracking mechansim from its "store" statement to determine which statement needs to be executed.
  • PIG is procedural and SQL is declarative. In fact, PIG looks a lot like a SQL query execution plan.
  • PIG enable easy plug-in of user defined functions
For more details, please refer to PIG's project site.

Constructors & Destructors of a Class in PHP

Constructors & Destructors of a Class in PHP


[Please read Introduction
to Classes in C++
, Introduction
to Constructor and Destructor Functions in C++
and Destructor
Functions in (C++) in Detail
to know more about Constructors and Destructors,
even though from C++’s perspective, they are useful nonetheless.]


Constructors


A constructor is a special member function of a class which is called automatically
when an object of the class is created. We can use it to perform useful initialization
such as giving initial values to member variables etc.


Unlike C++, PHP’s constructors always have the name ‘__construct’
and they can be defined as:


    function __construct()


    {

        ...


    }


Prior to PHP Version 5, constructors used to have the same name as of the class
(like in C++). Though PHP5 still understands constructors defined this way to
be backward compatible, it is advisable to use the new form.


e.g.


class myclass


{

    function 
__construct()


    {

        echo 
"Constructor Invoked Automatically!!";


    }

}


$ob=new myclass;


//prints "Constructor Invoked Automatically!!"


Parameterized Constructors


Constructors may also be defined to take parameters just like a regular function.
A typical parameterized constructor may be defined as below:


class myclass


{

    function 
__construct($arg)


    {

        echo 
"Constructor Invoked with Argument: $arg";


    }

}


And to create objects of such classes, we’d have to use the following
way:


$ob=new myclass(3);



Constructors may be defined to take any number of arguments just like a regular
function.


Destructors


The opposite of constructor is what we call a Destructor. As the name, it gets
called when an object is destructed (goes out of scope).


Similar to constructors, a destructor may be defined as:


    function __destruct()


    {

        ...


    }


One thing to note here is, destructors CANNOT take parameters, which is quite
obvious why.


Destructors may be used to close certain things such as files and MySQL connection
which the object used.


Previous Articles:


Object Oriented PHP...Creating and Using Classes

Object Oriented PHP…Creating and Using Classes


[Please Read Introduction
to Classes in C++
, Unit
Conversion Program using Classes
, A
Multi-Purpose String Class in C++
etc. for more information. Despite
being from C++'s perspective they're useful.]


In PHP a class is defined as following:


class myclass


{

    ...

    ...

}


For C/C++ programmers, do note that there’s no ‘;’ after
the closing curly brace.


A variable can be defined inside a class (AKA member variable) as:


class myclass


{

    
//notice the use of 'var'


    
var $var;


    ...

    ...

}


NOTE: We have to use ‘var’ keyword to define variables.


A function can also be defined inside a class as following. These functions
are known as Member Functions.


class myclass


{

    function 
myfunc()


    {

        echo 
"myfunc";


    }

    ...

    ...

}


Accessing Members


Classes as you might know is just like a user-defined data-type, they don’t
have any useful existence before we create instances or objects of that class.


Objects of a class may be created as:


$ob1=new myclass;


Now that ‘$ob1’ is an object of ‘myclass’ it holds
its copy of the member variables and functions declared in the class that can
be accessed as:


$ob1->var;



And functions as:


$ob1->myfunc();



Consider the following example code:


class myclass


{

    var 
$var;




    function 
myfunc()


    {

        echo 
"myfunc";


    }

}

$ob1=new myclass;


$ob2=new myclass;




$ob2->var=10;




echo 
$ob1->var;


$ob1->myfunc();


$ob2->myfunc();


Access Specifiers


You may control the accessibility of member variables and member functions
from outside the class using ‘Access Specifiers’. You have previously
seen that we can access members of a class using the following form:


echo $ob1->var;



And the members were accessible, because that is the default Access Specified
for all the members declared inside a class. So by default members of a class
have been given ‘public’ access from outside the class which can
also optionally be done using the ‘public’ keyword. Other access
specifies include ‘private’ and ‘protected’. Privately
declared members of a class are not accessible from outside the class (using
the ‘->’ method we have discussed). They however are accessible
only to other member functions of the same class. We’ll discuss about
‘protected’ access specifier in future posts as it first requires
‘inheritance’ to be discussed.


The following code illustrates it quite well:


class myclass2


{

    
//no 'var' keyword


    
private $var;




    function 
myfunc()


    {

        echo 
"myfunc";


        
$var=2;


        
// 'var' accessible to Member Function


        
echo $var;


    }

}



$ob1=new myclass2;




//not accessible

echo $ob1->var;




$ob1->myfunc();


Previous Articles:


Rewrite BASIC language today?

In the Usenet group alt.lang.basic there was a thread recently with the subject heading "Rewrite BASIC language today?" where the question was explored about how BASIC would be written in today's programming world.

Clearly there is a wide range of opinions in the responses. Some opted for being retro and simple. Some advocated adding commands for dealing with various things. It's good to have a discussion about these sorts of things, and this one went well. There are a lot of experienced BASIC programmers in that forum and it didn't turn into a flame war.

In my own response I wrote "BASIC needs to be simple. Adding C or Java features is a mistake for the most part. There is value in keeping things out of the language."

There needs to be a balance. Sometimes it makes good sense to add new things to a language. But as I just said... sometimes. ;-)

A Complete Note Keeping Application

A Complete Note Keeping Application


In this post we are going to expand the Note
Keeping Application
, using MySQL
to create a complete multi-user Application which would be able to register
new users
as well. It’d be a multi-user system hence many users
can register and work on their notes simultaneously. Each user’s data
will be private to them. It’d also have the missing features such as editing
and deleting of existing notes, hence a complete Note Keeping Application.


In a multi-user application we need to separate each user’s data so that
every user is shown only the data belonging to them. As we’ll be using
MySQL database to store data, one option is to create a table for each user,
it’d be good but when you have like thousands of users, having a table
for each is not very efficient.


There is one very efficient technique however, to separate data of different
users using relational database structure. For this we’ll only need two
tables for the whole application. One will store user-data along with an unique
userID (serialized) for each row (or user). The second table will store note
data, such as serial number, title, body etc. along with one more column to
store the userID (from table 1) to know the user storing the note. The following
image will clarify this:


Foreign Key and Primary Key


ID field was a Primary
Key
in the first table while when it appears in the second table to
make relation between the two tables; it is called a ‘foreign key’.
Please note that we are not doing anything special to create a foreign key,
just using a logical relation.


So with this structure any note getting stored has a valid ID (according to
the user who is logged in) in the userID field of the second (notes) table.
Thus each row in the second table is logically separated and related with the
user who has stored it.


Apart from multi-user functionality, we’re also integrating other features
like editing and deleting existing notes, which are done using the following
SQL
queries
:


For editing a note:


UPDATE <table-name> SET <column1=new-data1>,

<column2=new-data2>,



WHERE <column0=some-data>


For deleting a note:


DELETE FROM <table-name>

WHERE <some-column=some-data>


Now we have enough knowledge to see the code:


login.php:



<html>

<head>

<title>My Notes | Login</title>

</head>



<body>

<h1>My Notes</h1>

<h2>Login </h2>

<?php

//if submit button was pressed

//that means form was submitted

if(isset($_POST['submit']))

{

    
//connect to MySQL

    //change '-USER-' and '-PASS-'

    
$db=new mysqli('localhost','-USER-','-PASS-');

    
$db->select_db('one');



    
//fetch other form data

    
$username=trim($_POST['username']);

    
$password=trim($_POST['password']);

    

    
//start a session

    
session_start();

    
$result=$db->query("select pass from user where uname='$username'");

    if(
$result->num_rows>0

    {

        
$pass=$result->fetch_row();

        
$pass=$pass[0];

        if(
$password=$pass)

        {

            
//save session variable with the username

            //which will be unique

            
$_SESSION['user']=$username;

            
//redirect to homepage

            
header("Location: home.php");

        }

    }

    echo 
"<p style=\"color:#ff0000;\">Incorrect Username/Password. Please Try Again.</p>";

    
//close db connection

    
$db->close();

}

else

//requesting the login page

{

    
//if requesting the login page

    //check if already logged in

    //and redirect to homepage if true



    //start session

    
session_start();

    if(isset(
$_SESSION['user']))

    {

        
//redirect to homepage

        //if already logged in

        
header("Location: home.php");

    }

}

//if not logged in show the login page

?>

<form name="form1" id="form1" method="post" action="">

  <table width="30%" border="0" cellspacing="0" cellpadding="0">

    <tr> 

      <td>Username</td>

      <td><input name="username" type="text" id="username" /></td>

    </tr>

    <tr> 

      <td>Password</td>

      <td><input name="password" type="password" id="password" /></td>

    </tr>

    <tr>

      <td>&nbsp;</td>

      <td><input name="submit" type="submit" id="submit" value="Submit" /></td>

    </tr>

  </table>

</form>

<p>New User <a href="user_reg.php">Register Here</a></p>

</body>

</html>


user_reg.php: Please see Designing
a User-Registration Script in PHP
for this. Since this post has already
gotten so long.


home.php:



<html>

<head>

<title>My Notes</title>

</head>



<body>

<h1>My Notes</h1>

<p>Create A New Note</p>

<form name="form1" id="form1" method="post" action="home.php">

  <table width="100%" border="0" cellspacing="0" cellpadding="0">

    <tr> 

      <td width="22%"><font size="2">Title</font></td>

      <td width="78%"><input name="title" type="text" id="title" size="30"  /></td>

    </tr>

    <tr> 

      <td><font size="2">Body</font></td>

      <td><textarea name="body" cols="30" rows="7" id="body"></textarea></td>

    </tr>

    <tr> 

      <td><input name="post" type="submit" id="post" value="Post Note" /></td>

      <td><input type="reset" name="Submit2" value="Reset" /></td>

    </tr>

  </table>

</form>

<?php

//start session again

session_start();

//store the username

//that was stored by the login page

$uname=$_SESSION['user'];

//if someone is requesting this page

//without logging in

if(!isset($uname))

    
//redirect to login page

    
header('Location: login.php');

    

//connect to MySQL 

//provide your 'USERNAME' and 'PASSWORD' 

//change 'localhost' to the MySQL server 

//host, if not using on 'local server' 

$db=new mysqli('localhost','root','26519877');



//if this is the first time

//and database is not craeted

if(!$db->select_db('one'))

    
//create the database

    
$db->query('create database one');



//select the databasw to work with

$db->select_db('one');

            

//if table is not craeted, craete it

if(!$db->query('select * from notes'))

    
$db->query('create table notes(id int auto_increment primary key, title varchar(100), date varchar(50), body varchar(1000), userid int)');

        

//find the 'userid' from the user table

//it is the unique id of the logged in user

//it'd be needed to retrieve and save notes

$result=$db->query("select userid from user where uname='$uname'");

$result=$result->fetch_row();

$userid=$result[0];

    

//if logged in

echo "<p style=\"background: #000; color: #fff;\"><b>Hello: <i>".$_SESSION['user']."</b></i></p>";

echo 
"<a href=\"?action=logout\">Log Out</a></p>";



//----PERFORM ACTION AS PER WHAT WAS CLICKED----

//if 'post' button was pressed

//i.e note was posted

if(isset($_POST['post']))

{

    
$title=strip_tags($_POST['title']);

    
$body=strip_tags($_POST['body']);

    
//convert newlines in the body to <br />

    //so that formatting dont by user remains

    
$body=nl2br($body);

    
//have current date and time

    
$date=date('H:iA jS F Y');

    

    
//escape special characters that

    //can cause probs with MySQL

    
$title=addslashes($title);

    
$body=addslashes($body);

    
$date=addslashes($date);

    

    
//if body or title field was not blank

    
if($body!='' && $title!='')

        
//ready to insert data

        
$db->query("insert into notes (title, date, body, userid) values ('$title', '$date', '$body', '$userid')");

}

//if edit button was clicked on from the edit

//page

if(isset($_POST['edit']))

{

    
$title=strip_tags($_POST['title']);

    
$body=strip_tags($_POST['body']);

    
$date=strip_tags($_POST['date']);

    
//fetch the Note ID sent by the hiddeen form element

    
$id=trim($_POST['id']);

    

    
//convert newlines in the body to <br />

    //so that formatting dont by user remains

    
$body=nl2br($body);

    
//have current date and time

    

    //escape special characters that

    //can cause probs with MySQL

    
$title=addslashes($title);

    
$body=addslashes($body);

    
$date=addslashes($date);

    

    
//if body or title field was not blank

    
if($body!='' && $title!='')

        
//ready to updatedata

        
$db->query("update notes set title='$title', date='$date', body='$body' where id='$id'");

}



//if delete link is clicked w.r.t any note

if($_GET['action']=='del')

{

    
//have the ID of note to be deleted

    
$noteid=$_GET['id'];

    

    
$db->query("delete from notes where id='$noteid'");

}

//if logout was clicked

if($_GET['action']=='logout')

{

    unset(
$_SESSION['user']);

    
//redirect to login page

    
header('Location: login.php');

}

//----/ACTION PERFORMED----

    

//----SHOW THE PREVIOUS NOTES----

echo "<h2 style=\"background: #000; color: #fff;\">Previous Notes</h2>";

//fetch all the notes of the user

//'order by id desc' to have in newest first order

$result=$db->query("select * from notes where userid='$userid' order by id desc");

$num_rows=$result->num_rows;

for(
$i=0;$i<$num_rows;$i++)

{

    
$row=$result->fetch_row();

    
$id=$row[0];

    
$title=$row[1];

    
$date=$row[2];

    
$body=$row[3];

    

    
//we'd escaped special chars

    //so de-escaping those

    
$title=stripslashes($title);

    
$body=stripslashes($body);

    
$date=stripslashes($date);

    

    echo 
"<h3>$title</h3>

          <p><i>$date</i></p>

          <p>$body<br />"
;

    
//echo deleting option

    
echo "<a href=\"?action=del&id=$id\">Delete</a> | <a href=\"edit.php?id=$id\">Edit</a></p>";

}

//----/NOTES SHOWN----

$db->close();

?>

</body>

</html>


edit.php:



<?php

//fetch the unique note id sent

$id=(int)$_GET['id'];



//start session again

session_start();

//store the username

//that was stored by the login page

$uname=$_SESSION['user'];

//if someone is requesting this page

//without logging in

if(!isset($uname))

    
//redirect to login page

    
header('Location: login.php');

    

//connect to MySQL 

//provide your 'USERNAME' and 'PASSWORD' 

//change 'localhost' if required 

$db=new mysqli('localhost','root','26519877');



//select the databasw to work with

$db->select_db('one');



//query MySQL for the specific note

$result=$db->query("select * from notes where id='$id'");

//there will only be one note with an id

//fetch the row and its data

$result=$result->fetch_row();

$title=$result[1];

$date=$result[2];

$body=$result[3];



$db->close();

?>

<html>

<head>


<title>My Notes | Edit</title>

</head>



<body>

<h1>My Notes</h1>

<p>Edit Note</p>

<form name="form1" id="form1" method="post" action="home.php">

  <table width="100%" border="0" cellspacing="0" cellpadding="0">

    <tr> 

      <td width="22%"><font size="2">Title</font></td>

      <td width="78%"><input name="title" type="text" id="title" value="<?php echo $title?>" size="30"  /></td>

    </tr>

       

      <td>Date</td>

      <td><input name="date" type="text" id="date" value="<?php echo $date?>" size="30">

      <!-- hidden field is used for sending some information that user doesn't need to edit -->

      <!--here we are using it to send the ID of the note, it is needed to UPDATE the row -->

        <input name="id" type="hidden" id="id" value="<?php echo $id?>"></td>

    <tr> 

      <td><font size="2">Body</font></td>

      <td><textarea name="body" cols="30" rows="7" id="body"><?php echo $body?></textarea></td>

    </tr>

    <tr> 

      <td><input name="edit" type="submit" id="edit" value="Save Changes" /></td>

      <td><input type="reset" name="Submit2" value="Reset" /></td>

    </tr>

    <tr>

    </tr>

  </table>

</form>


Previous Articles:


Check out this stream